TypeError: Cannot read property 'authorization' of undefined using express-jwt
TypeError: Cannot read property 'authorization' of undefined using express-jwt
我正在尝试为我正在使用的路由添加身份验证 express-jwt
我添加了这个中间件来保护 post 创建路由。但是在测试时我在 postman.
中得到了错误
error
TypeError: Cannot read property 'authorization' of undefined<br> at Object.getTokenFromHeaders [as getToken]
这些是我的 express 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);
你在这行有错误:
const { headers: { authorization } } = req.body;
因为headers
prop是在req
对象上,而不是在req.body
上,所以应该是这样的:
const { headers: { authorization } } = req;
使用const authorization = req.headers.authorization
应该可以解决问题
这个解决方案帮助了我:
const { headers: { authorization } } = req;
const token = authorization && authorization.split(" ")[1];
我正在尝试为我正在使用的路由添加身份验证 express-jwt
我添加了这个中间件来保护 post 创建路由。但是在测试时我在 postman.
error
TypeError: Cannot read property 'authorization' of undefined<br> at Object.getTokenFromHeaders [as getToken]
这些是我的 express 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);
你在这行有错误:
const { headers: { authorization } } = req.body;
因为headers
prop是在req
对象上,而不是在req.body
上,所以应该是这样的:
const { headers: { authorization } } = req;
使用const authorization = req.headers.authorization
应该可以解决问题
这个解决方案帮助了我:
const { headers: { authorization } } = req;
const token = authorization && authorization.split(" ")[1];