如何访问“?"后的GET参数在快递? [英] How to access the GET parameters after "?" in Express?
问题描述
我知道如何为这样的查询获取参数:
I know how to get the params for queries like this:
app.get('/sample/:id', routes.sample);
在这种情况下,我可以使用req.params.id
来获取参数(例如/sample/2
中的2
).
In this case, I can use req.params.id
to get the parameter (e.g. 2
in /sample/2
).
但是,对于像 /sample/2?color=red
这样的 url,我如何访问变量 color
?
However, for url like /sample/2?color=red
, how can I access the variable color
?
我尝试了 req.params.color
但它没有用.
I tried req.params.color
but it didn't work.
推荐答案
所以,查看完快速参考,我发现 req.query.color
会返回我正在寻找的值.
So, after checking out the express reference, I found that req.query.color
would return me the value I'm looking for.
req.params 是指 URL 中带有 ':' 的项目,req.query 是指与 '?' 关联的项目
req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'
示例:
GET /something?color1=red&color2=blue
然后在 express 中,处理程序:
Then in express, the handler:
app.get('/something', (req, res) => {
req.query.color1 === 'red' // true
req.query.color2 === 'blue' // true
})
这篇关于如何访问“?"后的GET参数在快递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!