在 Express 中使用 URL 中的多个参数

我使用的是 Express 和 Node,我有一个需求,其中用户可以请求的 URL 为: http://myhost/fruit/apple/red

这样的请求将返回一个 JSON 响应。

JSON 数据,在上面的调用之前看起来像:

{
"fruit": {
"apple": "foo"
}
}

对于上述请求,响应 JSON 数据应该是:

{
"apple": "foo",
"color": "red"
}

我已经配置了特快路线如下:

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是否是正确的方式这样做。是吗?

202134 次浏览
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.

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}

Both of the way is correct you can use any of them First way

app.get('/fruit/:one/:two', function(req, res) {
console.log(req.params.one, req.params.two)
});


Another way using & symbol

app.get('/fruit/:one&:two', function(req, res) {
console.log(req.params.one, req.params.two)
});