node.js - 链接的中间件导致 Express 请求永远挂起

标签 node.js express middleware

我正在关注 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/

相关文章:

javascript - 如何在node.js express中的路由结束()之后停止中间件序列

node.js - Socket.io - 错误 : socket. 数据包不是函数

node.js - 我应该在哪里存储 jwt token 以在服务器端进行身份验证

node.js - node js - 我在使用 JSON.parse() 时遇到了一些问题

javascript - 如何解决语法错误: Unexpected token = after importing a class?

node.js - Expressjs 应用程序,使用 websockets 进行聊天。为 websocket 服务器使用不同的端口?

node.js - 如何使用 typescript 在 Node 中创建自定义中间件

node.js - NodeJS Sublime Text 构建系统

node.js - Node.js 中的多个 require ('express' )

node.js - 如何将socket.io附加到SwaggerExpress