我正在尝试使用express-jwt
添加路由身份验证,我添加了此中间件来保护发布后的路由。但是在测试时,我遇到了邮递员的错误。
错误
TypeError: Cannot read property 'authorization' of undefined<br> at Object.getTokenFromHeaders [as getToken]
这些是我的快递jwt代码
auth.js
import jwt from 'express-jwt';
const getTokenFromHeaders = (req) => {
const { headers: { authorization } } = req;
console.log(authorization); <----- in this log i am getting token
if(authorization && authorization.split(' ')[0] === 'Token') {
return authorization.split(' ')[1];
}
return null;
};
const auth = {
required: jwt({
secret: 'secret',
userProperty: 'payload',
getToken: getTokenFromHeaders,
}),
optional: jwt({
secret: 'secret',
userProperty: 'payload',
getToken: getTokenFromHeaders,
credentialsRequired: false,
}),
};
module.exports = auth;
routes.js
routes.post('/post', auth.required, postController.post);
答案 0 :(得分:1)
您在此行有一个错误:
const { headers: { authorization } } = req.body;
因为headers
道具位于req
对象上,而不位于req.body
上,所以应该这样:
const { headers: { authorization } } = req;
答案 1 :(得分:0)
使用const authorization = req.headers.authorization
应该可以解决问题