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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15128849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:43:08  来源:igfitidea点击:

Using multiple parameters in URL in express

node.jsexpress

提问by callmekatootie

I am using Express with Node and I have a requirement in which the user can request the URL as: http://myhost/fruit/apple/red.

我将 Express 与 Node 一起使用,并且我有一个要求,用户可以将 URL 请求为:http://myhost/fruit/apple/red

Such a request will return a JSON response.

这样的请求将返回一个 JSON 响应。

The JSON data, before the above call looks like:

上述调用之前的 JSON 数据如下所示:

{
    "fruit": {
        "apple": "foo"
    }
}  

With the above request, the response JSON data should be:

对于上述请求,响应 JSON 数据应为:

{
    "apple": "foo",
    "color": "red"
}

I have configured express to route as follows:

我已将 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*/
    });  

But this does not work. I am unsure of how to pass multiple parameters, that is, I am unsure if /fruit/:fruitName/:fruitColoris the correct way to do this. Is it?

但这不起作用。我不确定如何传递多个参数,也就是说,我不确定/fruit/:fruitName/:fruitColor这样做是否正确。是吗?

回答by chovy

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

如果这不起作用,请尝试使用 console.log(req.params) 看看它给你什么。

回答by Bandito11

For what you want I would've used

对于你想要的我会用

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
       const name = request.params.fruitName 
       const color = request.params.fruitColor 
    });

or better yet

或者更好

    app.get('/fruit/:fruit', function(request, response) {
       const fruit = request.params.fruit
       console.log(fruit)
    });

where fruit is a object. So in the client app you just call

水果是一个对象。所以在客户端应用程序中,您只需调用

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}

and as a response you should see:

作为回应,您应该看到:

    //  client side response
    // { name: My fruit name, color:The color of the fruit}