gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'authorization' of undefined using express-jwt

转载 作者:行者123 更新时间:2023-12-02 23:15:09 25 4
gpt4 key购买 nike

我正在尝试为我正在使用的express-jwt添加路由身份验证我添加了这个中间件来保护创建后的路由。但是在测试时我在 postman 中收到错误。

error

TypeError: Cannot read property &#39;authorization&#39; of undefined<br> &nbsp; &nbsp;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 属性位于 req 对象上,而不是 req.body 上,所以它应该是这样的:

const { headers: { authorization } } = req;

关于javascript - 类型错误 : Cannot read property &#39;authorization&#39; of undefined using express-jwt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com