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

我正在使用Express与节点,我有一个要求,用户可以请求的URL为: http://myhost/fruit/apple/red

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

上述调用之前的JSON数据如下所示:

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

有了上面的请求,响应JSON数据应该是:

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

我configuration了快速路由如下:

 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是否是正确的方法。 是吗?

 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)来查看它给你的东西。

为了你想要我会用

 app.get('/fruit/:fruitName&:fruitColor', function(request, response) { const name = request.params.fruitName const color = request.params.fruitColor }); 

或更好

  app.get('/fruit/:fruit', function(request, response) { const fruit = request.params.fruit console.log(fruit) }); 

水果是一个物体。 所以在客户端应用程序,你只是打电话

 https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"} 

作为回应,你应该看到:

  // client side response // { name: My fruit name, , color:The color of the fruit}