NodeJS:具有传统查询字符串格式的route.get

时间:2014-10-07 03:59:57

标签: node.js

我使用express来重定向我的网络请求。我的一个Web请求有三个可选参数,所以我有

router.get('/function/:param1?/:param2?/:param3?', function(req, res) {...}); 

我的问题是,因为所有这三个参数都是可选的而不是相互依赖。例如,用户只能提供param3。在当前实现中,由于路由器格式中嵌入的序列,param3将被分配给param1变量。

如何实现以下内容?

router.get('/function?param1=$1&param2=$2&param3=$3', function(req, res){...});

2 个答案:

答案 0 :(得分:6)

你必须使用req.query

正如express docs中所述,req.query是一个包含已解析查询字符串的对象,默认为{}

的示例:

// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"

// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"

req.query.shoe.color
// => "blue"

req.query.shoe.type
// => "converse"

您不应将查询参数放在路由中。你可以制作像

这样的路线
router.get('/function',function(req,res) {

    console.log(req.query);
    /*this will contain all the query string parameters as key/value in the object. 
    If you dint provide any in the URL, then it will be {}. */

    /* So a simple way to check if the url contains
    order as a query paramter will be like */
    if(typeof req.query.order != "undefined") {
        console.log(req.query.order);
    } else {
        console.log("parameter absent");
    }  

});

答案 1 :(得分:0)

像这样使用req.query:

router.get('/function', function(req, res) {
  var param1 = req.query.param1;
  var param2 = req.query.param2;
  var param3 = req.query.param3;
}); 

小心不要在/之后添加/function作为您的网址:

http://localhost/function?param1=xxparam2=yy&...

DOC