我正在使用Express with Node,我要求用户可以请求URL:http://myhost/fruit/apple/red
。
此类请求将返回JSON响应。
上述调用之前的JSON数据如下:
{
"fruit": {
"apple": "foo"
}
}
根据上述请求,响应JSON数据应为:
{
"apple": "foo",
"color": "red"
}
我已将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*/
});
但这不起作用。我不确定如何传递多个参数,也就是说,我不确定/fruit/:fruitName/:fruitColor
是否是正确的方法。是吗?
答案 0 :(得分:99)
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)查看它给你的内容。
答案 1 :(得分:9)
对于你想要的东西,我会用
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}