在URL中使用多个参数 [英] Using multiple parameters in URL in express

查看:108
本文介绍了在URL中使用多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express with Node,我有一个要求,用户可以在其中请求URL: http:// myhost / fruit / apple / red



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



上述电话之前的JSON数据如下所示:

  {
fruit:{
apple:foo
}
}

根据上述要求,响应JSON数据应为:

  {
apple:foo,
color:red
}

我已经配置了快递路由,如下所示:

  app.get('/ fruit /:fruitName / ',function(request,response){
/ *如上所述使用request.params.fruitName和
request.params.fruitColor返回响应JSON数据,以获取果苹果并将其颜色更新为红色* /
});

但这不行。我不确定如何传递多个参数,也就是说,我不确定 / fruit /:fruitName /:fruitColor 是否是正确的方法。是吗?

解决方案

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

send.json(data);
});

如果不行,请尝试使用console.log(req.params)查看它正在给你。


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.

Such a request will return a JSON response.

The JSON data, before the above call looks like:

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

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

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

I have configured express to route as follows:

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/:fruitColor is the correct way to do this. Is it?

解决方案

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.

这篇关于在URL中使用多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆