【发布时间】:2020-11-13 07:51:19
【问题描述】:
我正在尝试在我的 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、mongoose 一起用于我的数据库和打字稿。
我希望你能帮助我:)
【问题讨论】:
标签: json express authorization token request-headers