admin管理员组文章数量:1287581
I'm having an issue where, when a user tries to access an authorized route, I want to send a 401 status code and a JSON response describing the error to the client so I can handle it. The problem is that when the server returns a 401, it doesn't include the CORS headers, causing the browser to block any requests to that route. No amount of fetching or Axios will solve the problem, I am using Express for the backend and EJS templates/vanilla JavaScript on the client
SO the problem is iam trying to fetch the 401 response from the backend, but there is no fetch request visible in the browser's network tab. All I see is a red-colored route name with 'unauthorized access' in the network tab. The browser console also shows red text indicating 'unauthorized route with 401.' Also what I'm or the user will get on the frontend is the JSON returned by the authMiddleware.
**The authmdiddleware code **
import dotonev from 'dotenv';
dotonev.config();
import jwt from 'jsonwebtoken';
const authmiddleware = (req, res, next)=>{
const cookie = req.cookies?.token || req.headers['authorisation']
if(!cookie){
return res.status(401).json({error: 'unauthorised accses'});
}
try{
const decode = jwt.verify(cookie, process.env.jwt_SECRET);
req.user = decode
next()
}catch(err){
return res.status(403).json({ message: 'Forbidden: Invalid or expired token' });
}
};
export default authmiddleware;
And the Client code to fetch the 401 response
console.log(10)
document.addEventListener('DOMContentLoaded', async()=>{
let reach = await fetch('http://localhost:3000/home',{
method: 'GET',
credentials: 'include'
})
const respons = await reach.json()
console.log(respons)
if(data.error){
window.location.href = '/user/login';
return
}
const singup = document.getElementById('singup');
const login = document.getElementById('Login');
singup.addEventListener('click',()=>{
window.location.href = '/user/singup'
})
login.addEventListener('click',()=>{
window.location.href = '/user/login'
})
})
I'm new to this, so any help would be appreciated
本文标签: backendHandling JWT expiration or unauthorized accessStack Overflow
版权声明:本文标题:backend - Handling JWT expiration or unauthorized access - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741310291a2371612.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论