我正在尝试在我的API上发送jwt令牌,但它不起作用,而我做的事情与互联网课程相同。 看来授权标头是未定义的,不要拿我在json响应中给出的令牌。
这是我的登录功能的屏幕截图:
login(req:Request, res:Response) {
const id = this._id;
bcrypt.compare(req.query.password, this._password)
.then(function (valid: any) {
if (!valid) {
return res.status(401).json({error: 'Mot de passe incorrect !'});
}
res.status(200).json({
hostId: id,
token: jwt.sign({hostId : id}, 'RANDOM_TOKEN_SECRET', {expiresIn: '12h'})
});
})
.catch(function (error:any) {
res.status(500).json({error})
})
.catch(function (error:any) {
res.status(500).json({error});
});
}
这是我的身份验证功能:
static auth(req: Request, res: Response, next: any) {
try {
console.log('bonjour');
console.log(req.headers.authorization);
console.log(req.body.hostId);
let token = req.headers.authorization?.split(' ')[1];
const decodedToken = jwt.verify(token, 'RANDOM_TOKEN_SECRET');
const id = decodedToken.hostId;
if (req.body.hostId && req.body.hostId !== id) {
throw 'Invalid user ID';
} else {
next();
}
} catch (error) {
res.status(401).json({error: error.message});
}
}
我已经在服务器类中设置了标头:
export default class Server {
constructor() {
app.use(function (req:Request, res:Response, next:any) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization, Content-Type, Accept");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
})
.get('/', function (req:Request, res:Response) {
res.send("Serveur démarré");
})
.listen(8080);
}
}
我正在将nodejs和express,猫鼬用于我的数据库和打字稿。
我希望你能帮助我:)
答案 0 :(得分:1)
您应该在前端而不是服务器端将标头设置为{授权:Bearer ${token}
}