Node.js:req.query[] 和 req.params 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14417592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js: Difference between req.query[] and req.params
提问by JohnnyHK
Is there a difference between obtaining QUERY_STRING arguments via req.query[myParam]and req.params.myParam? If so, when should I use which?
通过req.query[myParam]和获取 QUERY_STRING 参数有区别req.params.myParam吗?如果是这样,我应该什么时候使用哪个?
回答by ruffrey
Given this route
鉴于这条路线
app.get('/hi/:param1', function(req,res){} );
and given this URL
http://www.google.com/hi/there?qs1=you&qs2=tube
并给出这个 URL
http://www.google.com/hi/there?qs1=you&qs2=tube
You will have:
你将会有:
req.query
要求。询问
{
qs1: 'you',
qs2: 'tube'
}
req.params
要求。参数
{
param1: 'there'
}
回答by JohnnyHK
req.paramscontains route parameters (in the path portion of the URL), and req.querycontains the URL query parameters (after the ?in the URL).
req.params包含路由参数(在 URL 的路径部分),并req.query包含 URL 查询参数(在?URL 之后)。
You can also use req.param(name)to look up a parameter in both places (as well as req.body), but this method is now deprecated.
您还可以使用req.param(name)在两个位置(以及req.body)中查找参数,但现在不推荐使用此方法。
回答by Deeksha Sharma
Suppose you have defined your route name like this:
假设您已经像这样定义了您的路线名称:
https://localhost:3000/user/:userid
which will become:
这将成为:
https://localhost:3000/user/5896544
Here, if you will print: request.params
在这里,如果您要打印: request.params
{
userId : 5896544
}
so
所以
request.params.userId = 5896544
so request.paramsis an object containing properties to the named route
所以request.params是一个包含命名路由属性的对象
and request.querycomes from query parameters in the URL eg:
和request.query来自 URL 中的查询参数,例如:
https://localhost:3000/user?userId=5896544
request.query
请求查询
{
userId: 5896544
}
so
所以
request.query.userId = 5896544
回答by Animesh Singh
You should be able to access the query using dot notation now.
您现在应该能够使用点表示法访问查询。
If you want to access say you are receiving a GETrequest at /checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XXand you want to fetch out the queryused.
如果您想访问,请说您正在接收一个GET请求,/checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XX并且您想取出所使用的查询。
var type = req.query.type,
email = req.query.email,
utm = {
source: req.query.utm_source,
campaign: req.query.utm_campaign
};
Paramsare used for the self defined parameter for receiving request, something like (example):
PARAMS被用于自定义的参数,用于接收请求,像(例如):
router.get('/:userID/food/edit/:foodID', function(req, res){
//sample GET request at '/xavg234/food/edit/jb3552'
var userToFind = req.params.userID;//gets xavg234
var foodToSearch = req.params.foodID;//gets jb3552
User.findOne({'userid':userToFind}) //dummy code
.then(function(user){...})
.catch(function(err){console.log(err)});
});
回答by Mile Mijatovi?
I want to mention one important note regarding req.query, because currently I am working on pagination functionality based on req.queryand I have one interesting example to demonstrate to you...
我想提一个关于 的重要说明req.query,因为目前我正在研究基于 的分页功能,req.query并且我有一个有趣的例子要向您展示......
Example:
例子:
// Fetching patients from the database
exports.getPatients = (req, res, next) => {
const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;
const patientQuery = Patient.find();
let fetchedPatients;
// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
/**
* Construct two different queries
* - Fetch all patients
* - Adjusted one to only fetch a selected slice of patients for a given page
*/
patientQuery
/**
* This means I will not retrieve all patients I find, but I will skip the first "n" patients
* For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
*
* Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
* so I want to skip (7 * (2 - 1)) => 7 items
*/
.skip(pageSize * (currentPage - 1))
/**
* Narrow dont the amound documents I retreive for the current page
* Limits the amount of returned documents
*
* For example: If I got 7 items per page, then I want to limit the query to only
* return 7 items.
*/
.limit(pageSize);
}
patientQuery.then(documents => {
res.status(200).json({
message: 'Patients fetched successfully',
patients: documents
});
});
};
You will noticed +sign in front of req.query.pageSizeand req.query.currentPage
你会注意到+前面的标志req.query.pageSize和req.query.currentPage
Why? If you delete +in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).
为什么?如果+在这种情况下删除,则会出现错误,并且会抛出该错误,因为我们将使用无效类型(错误消息“限制”字段必须为数字)。
Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.
重要提示:默认情况下,如果您从这些查询参数中提取某些内容,它将始终是 string,因为它来自 URL 并且被视为文本。
If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.
如果我们需要处理数字,并将查询语句从文本转换为数字,我们可以简单地在语句前添加一个加号。

