mongodb “JsonWeb令牌错误:jwt malformed”,为什么会出现此消息?如何解决此问题

mfuanj7w  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(226)

This is my code While I execute the code this "Not authorized, token failed" message is showing from the front end.

const asyncHandler = require("express-async-handler");
const User = require("../models/Staff.Model");
const jwt = require("jsonwebtoken");

const protect = asyncHandler(async (req, res, next) => { 
    let token

    if(req.headers.authorization && req.headers.authorization.startsWith('Bearer')){
       try{
           token = req.headers.authorization.split(' ')[1]
        const decoded = jwt.verify(token, process.env.JWT_SECRET)

        req.user =  await User.findById(decoded.id).select('-password')

        next()
       }catch (error){
           console.error(error)
           res.status(401)
           throw new Error('Not authorized, token failed')
       }
    }

    if(!token) {
        res.status(401)
        throw new Error('Not authorized, no token')
    }
})
yv5phkfx

yv5phkfx1#

我也面临着同样的问题。唯一的解决方案,我解决了这个问题后,许多心灵裂缝。你只需要使用关键字“返回“之前,每个“res“。我希望这将工作的其他人也。

相关问题