在 express 中使用 URL 中的多个参数 [英] Using multiple parameters in URL in express
问题描述
我在 Node 中使用 Express,我有一个要求,用户可以请求 URL 为:http://myhost/fruit/apple/red
.
I am using Express with Node and I have a requirement in which the user can request the URL as: http://myhost/fruit/apple/red
.
这样的请求将返回一个 JSON 响应.
Such a request will return a JSON response.
上述调用之前的JSON数据如下所示:
The JSON data, before the above call looks like:
{
"fruit": {
"apple": "foo"
}
}
有了上面的请求,响应的JSON数据应该是:
With the above request, the response JSON data should be:
{
"apple": "foo",
"color": "red"
}
我已将 express 配置为如下路由:
I have configured express to route as follows:
app.get('/fruit/:fruitName/:fruitColor', function(request, response) {
/*return the response JSON data as above using request.params.fruitName and
request.params.fruitColor to fetch the fruit apple and update its color to red*/
});
但这行不通.我不确定如何传递多个参数,也就是说,我不确定 /fruit/:fruitName/:fruitColor
是否是正确的方法.是吗?
But this does not work. I am unsure of how to pass multiple parameters, that is, I am unsure if /fruit/:fruitName/:fruitColor
is the correct way to do this. Is it?
推荐答案
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
如果这不起作用,请尝试使用 console.log(req.params) 看看它给了你什么.
If that doesn't work, try using console.log(req.params) to see what it is giving you.
这篇关于在 express 中使用 URL 中的多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!