我正在使用Express with Node,我要求用户可以将URL请求为:http://myhost/fruit/apple/red
.
这样的请求将返回JSON响应.
上述调用之前的JSON数据如下所示:
{
"fruit": {
"apple": "foo"
}
}
Run Code Online (Sandbox Code Playgroud)
根据上述请求,响应JSON数据应为:
{
"apple": "foo",
"color": "red"
}
Run Code Online (Sandbox Code Playgroud)
我已经配置了快递路线如下:
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*/
});
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我不确定如何传递多个参数,也就是说,我不确定这是否/fruit/:fruitName/:fruitColor
是正确的方法.是吗?
cho*_*ovy 112
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,请尝试使用console.log(req.params)来查看它给你的内容.
小智 14
对于你想要的我会用到的
app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
const name = request.params.fruitName
const color = request.params.fruitColor
});
Run Code Online (Sandbox Code Playgroud)
还是更好
app.get('/fruit/:fruit', function(request, response) {
const fruit = request.params.fruit
console.log(fruit)
});
Run Code Online (Sandbox Code Playgroud)
水果是一个对象.所以在客户端应用程序中,您只需致电
https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}
Run Code Online (Sandbox Code Playgroud)
作为回应你应该看到:
// client side response
// { name: My fruit name, color:The color of the fruit}
Run Code Online (Sandbox Code Playgroud)
两种方式都是正确的,您可以使用其中任何一种方式 第一种方式
app.get('/fruit/:one/:two', function(req, res) {
console.log(req.params.one, req.params.two)
});
Run Code Online (Sandbox Code Playgroud)
使用 & 符号的另一种方法
app.get('/fruit/:one&:two', function(req, res) {
console.log(req.params.one, req.params.two)
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
101612 次 |
最近记录: |