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


73

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

Answers:


137
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
你知道这样的事情是否可能吗? /fruit/:fruitName/vegetable/:vegetableName'
MadPhysicist's

2
当然。那样做就可以了,然后–req.params.fruitNamereq.params.vegetableName
chovy

1
它可以正常工作,但是碰巧/fruit在这种情况下将处理静态资源,例如/fruit/js/main.jspublic/js/main.js我的静态文件文件夹中。
loretoparisi

当缺少参数之一时,这将不起作用
Dipanshu Mahla

@chovy什么是调用此类端点的正确查询字符串?fruitName = $ {fruitName}&fruitColor = $ {fruitColor}
eran otzap

21

对于你想要的我会用

    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}

1
这似乎很好用,并且如果以后添加参数,则可以扩展。我在构建URL时在客户端做了JSON.stringify,并在路由中的服务器上做了JSON.parse。
james

嗯,是的。我忘记将JSON的.parse和.stringify添加到建议的答案中,但是在将对象作为参数传递时,我也做同样的事情,因此,我确定我将对象的正确形式传递为字符串。
Bandito11

1
请向我解释这是如何工作的?将字符串化的JSON作为参数传递给GET请求。这似乎是个坏主意。如果JSON超过GET char限制,那么您将要做什么?另外,如果JSON包含一些破坏URL编码的值,它将破坏(但是很容易解决)。
Edeph
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.