【问题标题】:Why adding a get parameter forces middleware execution为什么添加 get 参数会强制执行中间件
【发布时间】:2017-04-13 21:11:38
【问题描述】:

我有一个这样的中间件

// route middleware to verify a token
app.use(function(req, res, next) {

  console.log(req.baseUrl);

  // check header or url parameters or post parameters for token
  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  // decode token
  if (token) {

    // verifies secret and checks exp
    jwt.verify(token, app.get('superSecret'), function(err, decoded) {
      if (err) {
        return res.json({
          success: false,
          message: 'Failed to authenticate token.'
        });
      } else {
        // if everything is good, save to request for use in other routes
        req.decoded = decoded;
        next();
      }
    });

  } else {

    // if there is no token
    // return an error
    return res.status(403).send({
      success: false,
      message: 'No token provided.'
    });

  }
});

这条路线 http://localhost:8080/verifyAccount 不响应为 No token provided

app.get('/verifyAccount', function (req, res) {
  res.json({ message: 'Welcome to verify account!' });
});

但以下路线 http://localhost:8080/verifyAccount?id=123 可以:

app.get('/verifyAccount/:id', function (req, res) {
  res.json({ message: 'Welcome to verify account!' });
});

中间件代码在代码文件底部,获取路径在上

背后的概念是什么?

为什么添加 get 参数会强制执行中间件?

刚刚发现如果我这样称呼它http://localhost:8080/verifyAccount/id=123,它会正确返回Welcome to verify account!

【问题讨论】:

  • 我已经设置了一个非常基本的示例(只为每个路由和中间件提供 console.log 输出)。我可以看到从未调用过中间件。只有当请求“滴”到它的未知路由时才会调用它。您的代码一定有其他问题。
  • 啊,你的错误。带有查询参数?id=123 的请求与/:id 不匹配。应该是verifyAccount/123
  • @devnull69 如果我的参数名称是p1 那么我将如何称呼它?
  • 同理。位置决定参数,而不是名称。该名称仅在您的节点代码中用于引用参数
  • 你会有多个像verifyAccount/:id/:otherParameter这样的斜杠,可以使用verifyAccount/123/234调用

标签: javascript node.js express middleware


【解决方案1】:

发现问题出在调用路由的方式上。感谢Thomas Theiner 的帮助。

带有查询参数?id=123 的请求与/:id 不匹配。它应该被称为verifyAccount/123

因为,路由?id=123 没有匹配任何路径。因此,终于到达middleware 执行

位置决定参数,而不是名称。该名称仅在节点代码中用于引用参数。

对于多个参数,我们将有多个斜杠,例如 verifyAccount/:id/:otherParameter,将使用 verifyAccount/123/234 调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 2012-01-06
    • 2023-02-10
    • 2018-01-20
    相关资源
    最近更新 更多