node.js - NodeJS : route. 使用传统查询字符串格式获取

标签 node.js

我正在使用 Express 来重定向我的网络请求。我的一个网络请求接受三个可选参数,所以我有

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

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

如何实现如下所示的内容?

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

最佳答案

您必须使用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");
    }  

});

关于node.js - NodeJS : route. 使用传统查询字符串格式获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26228339/

相关文章:

javascript - Grunt/NPM Uglify 不喜欢这个 JS 行

node.js - 学习 NodeJS 和 MongoDB Docker 组合

linux - 我刚刚在运行 Ubuntu 的新服务器上运行我的新 node.js/express 应用程序,我如何查看我的 Web 应用程序?

javascript - 多行字符串作为参数

javascript - 该函数能否成功使其数据在其他上下文中可用?

javascript - AngularJs Http Post 未发布

node.js - 请求正文未从 aws-serverless-express 模块进入 app.js 文件

javascript - dynamodb.put().promise() 不返回放置对象

node.js - 有没有办法使用 express nodejs 打开一个新窗口

javascript - NodeJS 日期监听器然后回调