1
另一個noob問題。我使用JWT授權將用戶登錄到系統,獲取令牌並將其保存在localstorage
中,然後發送保存數據(基本上是一個大表單)的發佈請求。問題是,服務器在給定時間(20分鐘左右)後令該令牌無效,因此,我的一些帖子請求正在返回401 status
。如何在發送發佈請求之前驗證(如果需要,請顯示登錄提示)?我使用redux-form
來製作我的表格。 P:我知道我應該使用行動創造者等,但我仍然是一個新手,所以不太擅長這些東西。React - 在發送郵寄請求之前如何檢查JWT是否有效?
這裏是我的身份驗證:
export function loginUser(creds) {
const data = querystring.stringify({_username: creds.username, _password: creds.password});
let config = {
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: data
};
return dispatch => {
// We dispatch requestLogin to kickoff the call to the API
dispatch(requestLogin(creds));
return fetch(BASE_URL+'/login_check', config)
.then(response =>
response.json().then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
// If there was a problem, we want to
// dispatch the error condition
dispatch(loginError(user.message));
return Promise.reject(user)
} else {
// If login was successful, set the token in local storage
localStorage.setItem('id_token', user.token);
let token = localStorage.getItem('id_token')
console.log(token);
// Dispatch the success action
dispatch(receiveLogin(user));
}
}).catch(err => console.log("Error: ", err))
}
}
和這裏的POST
請求(我碰到redux-form
的values
對象)
const token = localStorage.getItem('id_token');
const AuthStr = 'Bearer '.concat(token);
let headers ={
headers: { 'Content-Type':'application/json','Authorization' : AuthStr }
};
export default (async function showResults(values, dispatch) {
axios.post(BASE_URL + '/new', values, headers)
.then(function (response) {
console.log(values);
console.log(response);
})
.catch(function (error) {
console.log(token);
console.log(values)
console.log(error.response);
});
});
PPS:如果任何人有改善我的代碼的任何建議,隨時發表評論。
非常感謝。在我開始工作後我會更新。 –