express: what is the difference between req.query and req.body

故事扮演 提交于 2020-12-29 00:15:48

问题


I want to know what is the difference between req.query and req.body?

below is a piece of code where req.query is used. what happens if i use req.body instead of req.query.

below function is called as a result of $resource get function. and this function checks whether the user is authenticated or a right user or not

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();
  });
});
}

回答1:


req.query contains the query params of the request.

For example in sample.com?foo=bar, req.query would be {foo:"bar"}

req.body contains anything in the request body. Typically this is used on PUT and POST requests.

For example a POST to sample.com with the body of {"foo":"bar"} and a header of type application/json, req.body would contain {foo: "bar"}

So to answer your question, if you were to use req.body instead of req.query, it would most likely not find anything in the body, and therefore not be able to validate the jwt.

Hope this helps.




回答2:


req.body is mainly used with form using POST method. You've to use enctype="application/x-www-form-urlencoded" in the form properties. As POST method don't show anything in URL, you have to use body-parser middleware if the form contains an input text with name="age" then req.body.age return the value of this feld.

req.query takes parameters in the URL (mainly GET method) example for this URL ► http://localhost/books?author=Asimov app.get('/books/', (req, res) => { console.log(req.query.author) } will return Asimov

by the way, req.params take the end part of the URL as a parameter. example for this URL ► http://localhost/books/14 app.get('/books/:id', (req, res) => { console.log(req.params.id) } will return 14



来源:https://stackoverflow.com/questions/30915424/express-what-is-the-difference-between-req-query-and-req-body

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!