【问题标题】:express: what is the difference between req.query and req.bodyexpress: req.query 和 req.body 有什么区别
【发布时间】:2015-06-18 12:31:06
【问题描述】:

我想知道req.query和req.body有什么区别?

下面是一段代码,其中使用了req.query。如果我使用req.body 而不是req.query 会发生什么。

$resource get 函数调用了下面的函数。并且这个函数会检查用户是否经过身份验证或者是正确的用户

function isAuthenticated() {
return compose()
// Validate jwt
.use(function(req, res, next) {
  // allow access_token to be passed through query parameter as well
  if(req.query && req.query.hasOwnProperty('access_token')) {
    req.headers.authorization = 'Bearer ' + req.query.access_token;
  }
  validateJwt(req, res, next);
})
// Attach user to request
.use(function(req, res, next) {
  User.findById(req.user._id, function (err, user) {
    if (err) return next(err);
    if (!user) return res.send(401);

    req.user = user;
    next();
  });
});
}

【问题讨论】:

    标签: express


    【解决方案1】:

    req.query 包含请求的查询参数。

    例如在sample.com?foo=bar 中,req.query 将是{foo:"bar"}

    req.body 包含请求正文中的任何内容。这通常用于PUTPOST 请求。

    例如,POST 到 sample.com 的正文为 {"foo":"bar"},标头类型为 application/jsonreq.body 将包含 {foo: "bar"}

    所以要回答您的问题,如果您使用 req.body 而不是 req.query,它很可能在正文中找不到任何东西,因此无法验证 jwt。

    希望这会有所帮助。

    【讨论】:

    • req.params 呢?您还可以指定 req.params 与 req.body 与 req.query 之间的区别吗?
    • 这是一个不同的问题,应该这样询问(或搜索)。 (params 用于 url 值,例如 /user/:id -> req.params.id)
    【解决方案2】:

    req.body 主要用于使用 POST 方法的表单。 您必须在表单属性中使用enctype="application/x-www-form-urlencoded"。由于 POST 方法在 URL 中不显示任何内容,因此您必须使用 body-parser 中间件 如果表单包含 name="age" 的输入文本,则 req.body.age 返回此字段的值。

    req.query 在 URL 中取参数(主要是 GET 方法) 此 URL 的示例 ► http://localhost/books?author=Asimov app.get('/books/', (req, res) => { console.log(req.query.author) } 将返回阿西莫夫

    顺便说一下,req.params 将 URL 的结尾部分作为参数。 此 URL 的示例 ► http://localhost/books/14 app.get('/books/:id', (req, res) => { console.log(req.params.id) } 将返回 14

    【讨论】:

      猜你喜欢
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 2014-06-27
      • 2020-02-23
      相关资源
      最近更新 更多