【问题标题】:Using multiple parameters in URL in express在 express 中使用 URL 中的多个参数
【发布时间】:2013-02-28 06:22:51
【问题描述】:

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

【问题讨论】:

    标签: node.js express


    【解决方案1】:
    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) 看看它给了你什么。

    【讨论】:

    • 你知道这样的事情是否可行吗? /fruit/:fruitName/vegetable/:vegetableName'
    • 当然。就那样做然后做req.params.fruitNamereq.params.vegetableName
    • 它可以工作,但在这种情况下,静态资源将在/fruit 下处理,例如/fruit/js/main.js,其中我有public/js/main.js 作为我的静态文件夹。
    • 当缺少其中一个参数时这不起作用
    • @chovy 调用此类端点的正确查询字符串是什么?fruitName=${fruitName}&fruitColor=${fruitColor}
    【解决方案2】:

    你想要什么我都会用

        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}
    

    【讨论】:

    • 这似乎工作得很好,如果您稍后添加参数,则更具可扩展性。在路由中的服务器上构建 URL 和 JSON.parse 时,我在客户端做了一个 JSON.stringify。
    • 啊,你说得对。我忘记将 JSON 的 .parse 和 .stringify 添加到我建议的答案中,但是在将对象作为参数传递时我也会这样做,所以我确信我将对象的正确形式作为字符串传递。
    • 请解释一下这是如何工作的?将字符串化的 JSON 作为参数提供给 GET 请求。这似乎是一个非常糟糕的主意。如果 JSON 超过了 GET char 限制,那么你要做什么?此外,如果 JSON 包含一些破坏 URL 编码的值,它将破坏(但这很容易修复)。
    【解决方案3】:

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

    app.get('/fruit/:one/:two', function(req, res) {
        console.log(req.params.one, req.params.two)
    });
    
    

    使用 & 符号的另一种方式

    app.get('/fruit/:one&:two', function(req, res) {
        console.log(req.params.one, req.params.two)
    });
    

    【讨论】:

      猜你喜欢
      • 2019-01-20
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      相关资源
      最近更新 更多