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')
}
})
1条答案
按热度按时间yv5phkfx1#
我也面临着同样的问题。唯一的解决方案,我解决了这个问题后,许多心灵裂缝。你只需要使用关键字“返回“之前,每个“res“。我希望这将工作的其他人也。