表达:req.query和req.body有什么区别 [英] express: what is the difference between req.query and req.body
问题描述
我想知道req.query和req.body有什么区别?
I want to know what is the difference between req.query and req.body?
是一段使用 req.query
的代码.如果我使用 req.body
而不是 req.query
,会发生什么.
below is a piece of code where req.query
is used. what happens if i use req.body
instead of req.query
.
下面的函数是 $ resource
get函数的结果.并且此功能检查用户是否已通过身份验证或正确的用户
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();
});
});
}
推荐答案
要求.query 包含请求的查询参数.
req.query contains the query params of the request.
例如在 sample.com?foo=bar
中, req.query
将是 {foo:"bar"}
req.body 在请求正文中包含任何内容.通常,它用于 PUT
和 POST
请求.
req.body contains anything in the request body. Typically this is used on PUT
and POST
requests.
例如要进入sample.com的 POST
,其正文为 {"foo":"bar"}
,标题为 application/json
, req.body
将包含 {foo:"bar"}
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"}
所以要回答您的问题,如果您要使用 req.body
而不是 req.query
,则很可能在体内找不到任何东西,因此无法验证jwt.
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.
希望这会有所帮助.
这篇关于表达:req.query和req.body有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!