admin管理员组文章数量:1388105
I recently discovered that using credentials: "include" successfully prevents the cookie from being accessed by JavaScript, and it works as expected. However, I encountered an issue where, upon JWT session expiration, the backend returns a 401 Unauthorized error. While a 401 error is commonly used for authentication issues, it may not be the most ideal way to handle token expiration. This is because a 401 error could also result from role-based access restrictions, which would make redirecting to the /login page inappropriate in such cases. Therefore, a more refined approach is needed to distinguish between these scenarios and handle them accordingly.
I'm using React as Frontend and Spring as Backend
Below is one such request:
const handleLoginRequest = async (e) => {
try {
const response = await fetch('http://localhost:3000/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-XSRF-TOKEN': csrfToken || "",
},
body: JSON.stringify(formData),
credentials: 'include'
});
console.log(response)
const data=await response.json()
console.log(data)
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || 'Login failed');
}
console.log('Login successful!');
} catch (err) {
setError(err.message);
}
};
本文标签:
版权声明:本文标题:reactjs - How to manage token expiration when adding "credentials: include" at React api requests - Stack Over 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744500499a2609292.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论