Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在express的URL中使用多个参数_Node.js_Express - Fatal编程技术网

Node.js 在express的URL中使用多个参数

Node.js 在express的URL中使用多个参数,node.js,express,Node.js,Express,我正在使用带有节点的Express,我有一个要求,即用户可以请求URL:http://myhost/fruit/apple/red 这样的请求将返回一个JSON响应 上述调用之前的JSON数据如下所示: { "fruit": { "apple": "foo" } } 对于上述请求,响应JSON数据应为: { "apple": "foo", "color": "red" } 我已将express配置为如下路线: app.get('/fruit

我正在使用带有节点的Express,我有一个要求,即用户可以请求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
是否是正确的方法。是吗

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',函数(请求、响应){
const name=request.params.froutname
const color=request.params.fruitColor
});
或者更好

app.get('/fruit/:fruit',函数(请求、响应){
const fruit=request.params.fruit
原木(水果)
});
其中水果是一个对象。因此,在客户端应用程序中,您只需调用

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}
作为回应,你应该看到:

//客户端响应
//{名称:我的水果名称,颜色:水果的颜色}

您知道这样做是否可行吗<代码>/fruit/:fruitName/vegetableName'当然可以。就这样做,然后做
req.params.fruitName
req.params.vegetableName
它就可以工作了,但是,在本例中,静态资源将在
/fruit
下寻址,就像
/fruit/js/main.js
中我将
public/js/main.js
作为静态文件文件夹一样。当其中一个参数为missing@chovy调用这样一个端点的正确查询字符串是什么&fruitColor=${fruitColor}这似乎工作得很好,如果以后添加参数,它的扩展性会更好。在路由中构建URL和服务器上的JSON.parse时,我在客户端执行了JSON.stringify。啊,你说得对。我忘了在我的建议答案中添加JSON的.parse和.stringify,但我在将对象作为参数传递时也做了同样的操作,因此我确信我将对象的正确形式作为字符串传递。请向我解释这是如何工作的?将字符串化JSON作为参数提供给GET请求。这似乎是个非常糟糕的主意。如果JSON超过了GET char限制,那么您将怎么做?此外,如果JSON包含一些破坏URL编码的值,它将被破坏(但这很容易修复)。