【发布时间】:2013-01-03 06:22:07
【问题描述】:
通过req.query[myParam] 和req.params.myParam 获取QUERY_STRING 参数有区别吗?如果是这样,我应该什么时候使用哪个?
【问题讨论】:
标签: node.js query-string
通过req.query[myParam] 和req.params.myParam 获取QUERY_STRING 参数有区别吗?如果是这样,我应该什么时候使用哪个?
【问题讨论】:
标签: node.js query-string
假设你已经这样定义你的路由名称:
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
【讨论】:
我只想补充一点,如果您来自axios,(GET/POST)您可以通过配置使用query/url params(使用req.query 读取):
axios.post('/users', {...data}, {
headers: {...anyHeaders},
params: {uid: `${uid}`}
})
然后您通过路径使path/route variables(使用req.params 可读)可用:
axios.get(`/users/${uid`}, {
headers: {...anyHeaders}
})
我还要补充一点,用于在服务器上读取查询参数的名称必须与来自客户端的名称匹配。如果路径/路由的一部分可用(基本上是进行替换 - 有点像 react-router 的做法:/path/:variable),则路径变量的情况并非如此,因为路径变量可以在服务器上使用任何名称。
【讨论】:
我想提一个关于 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前面的标志
为什么?如果你在这种情况下删除+,你会得到一个错误,并且会抛出该错误,因为我们将使用无效类型(错误消息'limit'字段必须是数字)。
重要提示:默认情况下,如果您从这些查询参数中提取某些内容,它将始终为字符串,因为它来自 URL 并且被视为文本。
如果我们需要处理数字,并将查询语句从文本转换为数字,我们可以简单地在语句前面添加一个加号。
【讨论】:
您现在应该可以使用点表示法访问查询了。
如果你想访问,说你在/checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XX 收到一个GET 请求,并且你想获取所使用的查询。
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.params 包含路由参数(在 URL 的路径部分),req.query 包含 URL 查询参数(在 URL 中的 ? 之后)。
您也可以使用req.param(name) 在这两个位置(以及req.body)查找参数,但此方法现在已弃用。
【讨论】:
req.param 现在已弃用。 Node 建议使用req.query 或req.params
鉴于这条路线
app.get('/hi/:param1', function(req,res){} );
并给出这个 URL
http://www.google.com/hi/there?qs1=you&qs2=tube
你将拥有:
req.查询
{
qs1: 'you',
qs2: 'tube'
}
req.参数
{
param1: 'there'
}
【讨论】:
/上拆分