表达:req.query和req.body之间有什么区别

Jas*_*ngh 2 express

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

下面是一段使用的代码req.query.如果我使用req.body而不是req.query.

由于$resourceget函数调用下面的函数.此功能检查用户是否经过身份验证或是否是正确的用户

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();
  });
});
}
Run Code Online (Sandbox Code Playgroud)

Bre*_*nan 13

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

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

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

例如POST,以与sample.com的主体{"foo":"bar"}和类型的报头application/json,req.body将包含{foo: "bar"}

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

希望这可以帮助.


Dav*_*NET 5

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

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

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