我正在尝试在JWT
应用程序中使用node.js
。我关注了this tutorial。
但是我在中间件方面面临问题:
function authenticateToken(req, res, next)
在视频中的10:30的时间。
当我运行代码时,我总是有:
authHeader == null
我已经尝试了各种方法来为req.headers ['authorization]查找其他可能的形式,例如req.headers.authorization,但无济于事。
我需要说的是,我的应用程序中有一条路由,允许我登录,并且在使用路由打中间件之前就已经使用了。但无论如何,authHeader始终为null。
我应该怎么做才能确保获得预期的有效AuthHeader,以使该应用程序能够像本教程中所述一样工作并向前发展?
如果可能有用,这是中间件功能的完整代码:
function authenticateToken(req, res, next) {
// Get the jwt access token from the request header.
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) {
console.log('authenticateToken-401')
return res.sendStatus(401)
}
jwt.verify(token, 'myBigSecret', (err, user) => {
console.log(err)
if (err) {
console.log('authenticateToken-403')
return res.sendStatus(403)
}
req.user = user
next()
})
}
您需要在请求中设置标题,看起来您没有在请求中设置标题