我正在关注 this question 中的中间件链接示例.
我有一条路线 app.put('/users/:id', isAuthenticated, (req, res) => {db.updateUser(req.params.id, req.body)}
. 我正在尝试编写一个中间件函数,用于验证 URL 中提供的 ID 是否与从请求中包含的 JWT 检索到的 ID 相匹配。
我已经有一个函数 isAuthenticated
来验证 JWT 并将 res.locals.userId
设置为检索到的 UID;所以我想简单地在这个新函数 canModifyTarget
中使用它,但由于某种原因,请求永远挂起:
// This function works fine
isAuthenticated: function(req, res, next) {
let token;
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
token = req.headers.authorization.split(' ')[1];
admin.auth().verifyIdToken(token).then((decodedToken) => {
res.locals.userId = decodedToken.uid;
return next();
}).catch((error) => {
return res.status(HttpStatus.UNAUTHORIZED).send();
})
}
}
<小时/>
// Switching out isAuthenticated for this in the route causes a permanent hang
canModifyTarget: function(req, res, next) {
console.log('This is printed');
return (req, res, next) => {
console.log('This is NOT printed');
isAuthenticated(req, res, () => {
if (req.params.id === res.locals.userId) {
return next();
}
return res.status(HttpStatus.FORBIDDEN).send();
})
}
}
最佳答案
中间件应该是回调函数,一旦完成就调用“next()”。 您的第一个函数在执行时正在调用 next() (最终,在您的 promise 得到解决后)
你的第二个函数没有调用 next(),它只是返回一个函数定义。
这样定义
canModifyTarget: function(req, res, next) {
isAuthenticated(req, res, () => {
if (req.params.id === res.locals.userId) {
return next();
}
return res.status(HttpStatus.FORBIDDEN).send();
})
}
}
如果 isAuthenticated 的第三个参数是回调,那么它应该可以工作
此外,您应该在 isAuthenticated
函数中定义一个“else”情况,否则它也会挂起(可能会抛出异常或其他什么?)
如果您需要引用它们,请将它们存储在变量中,而不是直接在 module.exports 中定义它们:
const isAuthenticated = function(req, res, next) {
// code here
}
const canModifyTarget: function(req, res, next) {
// code here
}
module.exports = {
isAuthenticated,
canModifyTarget,
};
关于node.js - 链接的中间件导致 Express 请求永远挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52584148/