Answers:
req.params
包含路由参数(在URL的路径部分中),并req.query
包含URL查询参数(在?
URL中的后面)。
您也可以使用req.param(name)
来在这两个地方(以及req.body
)查找参数,但是现在不建议使用此方法。
req.param
现在已弃用。节点建议使用req.query
或req.params
鉴于这条路线
app.get('/hi/:param1', function(req,res){} );
并给出了这个URL
http://www.google.com/hi/there?qs1=you&qs2=tube
您将拥有:
要求 询问
{
qs1: 'you',
qs2: 'tube'
}
要求 参数
{
param1: 'there'
}
/
假设您这样定义了路由名称:
https://localhost:3000/user/:userid
它将变成:
https://localhost:3000/user/5896544
在这里,如果您要打印: request.params
{
userId : 5896544
}
所以
request.params.userId = 5896544
因此request.params是一个对象,其中包含命名路由的属性
和request.query来自URL中的查询参数,例如:
https://localhost:3000/user?userId=5896544
request.query
{
userId: 5896544
}
所以
request.query.userId = 5896544
您现在应该可以使用点符号来访问查询。
如果您要访问,则说您在处收到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
};
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)});
});
我想提一个有关的重要说明req.query
,因为目前我正在基于进行分页功能,req.query
并且有一个有趣的示例向您展示...
例:
// 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
});
});
};
您会注意到和+
前面的标志req.query.pageSize
req.query.currentPage
为什么?如果+
在这种情况下删除,则会收到错误消息,并且会抛出该错误消息,因为我们将使用无效的类型(错误消息“限制”字段必须为数字)。
重要提示:默认情况下,如果您从这些查询参数中提取内容,则该内容将始终为字符串,因为它来自URL,并且被视为文本。
如果需要处理数字,并将查询语句从文本转换为数字,则只需在语句前面添加加号即可。