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