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

cal*_*tie 60 node.js express

我正在使用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)来查看它给你的内容.

  • 你知道这样的事情是否可能吗?`/fruit/:fruitName/vegetable/:vegetableName'` (2认同)
  • 当然.就这样做,然后做`req.params.fruitName`和`req.params.vegetableName` (2认同)

小智 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)

  • 请向我解释这是如何工作的?将字符串化的 JSON 作为参数提供给 GET 请求。这似乎是一个非常糟糕的主意。如果 JSON 超过了 GET 字符限制,那么你会怎么做?此外,如果 JSON 包含一些破坏 URL 编码的值,它就会破坏(但这很容易修复)。 (2认同)

MD *_*YON 7

两种方式都是正确的,您可以使用其中任何一种方式 第一种方式

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)