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:如果任何人有改善我的代码的任何建议,随时发表评论。
非常感谢。在我开始工作后我会更新。 –