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
.
我使用的是Express with Node,我有一个要求,用户可以将URL请求为:http://myhost/fruit/apple/red。
Such a request will return a JSON response.
这样的请求将返回JSON响应。
The JSON data, before the above call looks like:
以上调用前的JSON数据如下:
{
"fruit": {
"apple": "foo"
}
}
With the above request, the response JSON data should be:
对于上述请求,响应JSON数据应该是:
{
"apple": "foo",
"color": "red"
}
I have configured express to route as follows:
我将express配置为以下路线:
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*/
});
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?
但这行不通。我不确定如何传递多个参数,也就是说,我不确定是否/水果/:水果名/:水果色是正确的方法。是吗?
2 个解决方案
#1
77
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
如果不行,可以使用console.log(req.params)来查看它提供的内容。
#2
4
For what you want I would've used
你要什么我就用什么
app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
const name = request.params.fruitName
const color = request.params.fruitColor
});
or better yet
或者更好的是
app.get('/fruit/:fruit', function(request, response) {
const fruit = request.params.fruit
console.log(fruit)
});
where fruit is a object. So in the client app you just call
水果是物体。在客户端应用中,你只需要调用
https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}
and as a response you should see:
作为回应你应该看到:
// client side response
// { name: My fruit name, , color:The color of the fruit}
#1
77
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
如果不行,可以使用console.log(req.params)来查看它提供的内容。
#2
4
For what you want I would've used
你要什么我就用什么
app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
const name = request.params.fruitName
const color = request.params.fruitColor
});
or better yet
或者更好的是
app.get('/fruit/:fruit', function(request, response) {
const fruit = request.params.fruit
console.log(fruit)
});
where fruit is a object. So in the client app you just call
水果是物体。在客户端应用中,你只需要调用
https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}
and as a response you should see:
作为回应你应该看到:
// client side response
// { name: My fruit name, , color:The color of the fruit}