【问题标题】:How to access the GET parameters after "?" in Express?如何访问“?”之后的 GET 参数在快递?
【发布时间】:2013-06-05 04:06:33
【问题描述】:

我知道如何获取这样的查询的参数:

app.get('/sample/:id', routes.sample);

在这种情况下,我可以使用req.params.id 来获取参数(例如/sample/2 中的2)。

但是,对于像 /sample/2?color=red 这样的 url,我如何访问变量 color

我试过req.params.color,但没用。

【问题讨论】:

    标签: node.js express query-string


    【解决方案1】:

    所以,在查看了express reference 之后,我发现req.query.color 会返回我正在寻找的值。

    req.params 指的是 URL 中带有“:”的项目,req.query 指的是与“?”关联的项目

    例子:

    GET /something?color1=red&color2=blue
    

    然后在 express 中,处理程序:

    app.get('/something', (req, res) => {
        req.query.color1 === 'red'  // true
        req.query.color2 === 'blue' // true
    })
    

    【讨论】:

    • 您能告诉我如何验证“id”吗?
    • @AnandRaj:你是什么意思:如何验证“id”?你想要什么样的验证?顺便说一句,您可以像这样在函数中获取id 的值:var sampleId = req.params.id;
    • 在最新版本中使用req.params.whatever
    • 请注意req.paramsreq.query 不同! expressjs.com/en/api.html#req.paramsexpressjs.com/en/api.html#req.query@adelriosantiago
    • 我不相信这个答案(来自 OP)实际上回答了他自己的原始问题!他清楚地询问如何在结合位置参数 (:id) 中访问查询字符串值。我有完全相同的问题,这个答案没有提供解决方案?!
    【解决方案2】:

    更新: req.param() 现已弃用,因此今后不要使用此答案。


    您的回答是首选的方法,但我想我想指出您也可以使用req.param(parameterName, defaultValue) 访问 url、post 和 route 参数。

    在你的情况下:

    var color = req.param('color');
    

    来自快递指南:

    查找按以下顺序执行:

    • req.params
    • req.body
    • req.query

    请注意,指南确实说明了以下内容:

    直接访问 req.body、req.params 和 req.query 应该是 为清楚起见而受到青睐 - 除非您真正接受来自每个对象的输入。

    但在实践中,我发现req.param() 足够清晰,并且使某些类型的重构更容易。

    【讨论】:

      【解决方案3】:

      @Zugwait 的回答是正确的。 req.param() 已弃用。您应该使用req.paramsreq.queryreq.body

      但只是为了更清楚:

      req.params 将仅填充路由值。也就是说,如果您有类似/users/:id 的路由,则可以在req.params.idreq.params['id'] 中访问id

      req.queryreq.body 将使用 all 参数填充,无论它们是否在路由中。当然,查询字符串中的参数将在req.query 中可用,帖子正文中的参数将在req.body 中可用。

      所以,回答您的问题,因为color 不在路线中,您应该可以使用req.query.colorreq.query['color'] 获得它。

      【讨论】:

        【解决方案4】:

        快速手册说您应该使用req.query 来访问QueryString。

        // Requesting /display/post?size=small
        app.get('/display/post', function(req, res, next) {
        
          var isSmall = req.query.size === 'small'; // > true
          // ...
        
        });
        

        【讨论】:

          【解决方案5】:

          查询字符串和参数不同。

          您需要在单个路由 url 中同时使用两者

          请检查下面的示例可能对您有用。

          app.get('/sample/:id', function(req, res) {
          
           var id = req.params.id; //or use req.param('id')
          
            ................
          
          });
          

          获取传递第二段的链接是您的 id 示例:http://localhost:port/sample/123

          如果您遇到问题,请使用“?”作为查询字符串传递变量运营商

            app.get('/sample', function(req, res) {
          
               var id = req.query.id; 
          
                ................
          
              });
          

          获取您喜欢的链接:http://localhost:port/sample?id=123

          两者都在一个例子中

          app.get('/sample/:id', function(req, res) {
          
           var id = req.params.id; //or use req.param('id')
           var id2 = req.query.id; 
            ................
          
          });
          

          获取链接示例:http://localhost:port/sample/123?id=123

          【讨论】:

          • 感谢这个答案很有帮助!
          【解决方案6】:

          使用 req.query,获取路由中查询字符串参数中的值。 请参阅req.query。 假设在路由中,http://localhost:3000/?name=satyam 您想获取 name 参数的值,那么您的“获取”路由处理程序将如下所示:-

          app.get('/', function(req, res){
              console.log(req.query.name);
              res.send('Response send to client::'+req.query.name);
          
          });
          

          【讨论】:

          • 也许一些关于查询字符串的信息以获得完整的答案
          【解决方案7】:

          我已经开始在 express 上的一些应用程序中使用的一个很好的技术是创建一个对象,该对象合并 express 请求对象的查询、参数和正文字段。

          //./express-data.js
          const _ = require("lodash");
          
          class ExpressData {
          
              /*
              * @param {Object} req - express request object
              */
              constructor (req) {
          
                  //Merge all data passed by the client in the request
                  this.props = _.merge(req.body, req.params, req.query);
               }
          
          }
          
          module.exports = ExpressData;
          

          然后在您的控制器主体中,或在快速请求链范围内的任何其他地方,您可以使用如下内容:

          //./some-controller.js
          
          const ExpressData = require("./express-data.js");
          const router = require("express").Router();
          
          
          router.get("/:some_id", (req, res) => {
          
              let props = new ExpressData(req).props;
          
              //Given the request "/592363122?foo=bar&hello=world"
              //the below would log out 
              // {
              //   some_id: 592363122,
              //   foo: 'bar',
              //   hello: 'world'
              // }
              console.log(props);
          
              return res.json(props);
          });
          

          这使得“深入研究”用户可能随请求发送的所有“自定义数据”变得既方便又方便。

          注意

          为什么是“道具”字段?因为那是一个精简的 sn-p,所以我在我的许多 API 中都使用了这种技术,我还将身份验证/授权数据存储到这个对象上,示例如下。

          /*
           * @param {Object} req - Request response object
          */
          class ExpressData {
          
              /*
              * @param {Object} req - express request object
              */
              constructor (req) {
          
                  //Merge all data passed by the client in the request
                  this.props = _.merge(req.body, req.params, req.query);
          
                  //Store reference to the user
                  this.user = req.user || null;
          
                  //API connected devices (Mobile app..) will send x-client header with requests, web context is implied.
                  //This is used to determine how the user is connecting to the API 
                  this.client = (req.headers) ? (req.headers["x-client"] || (req.client || "web")) : "web";
              }
          } 
          

          【讨论】:

          • 这可能是个坏主意,因为它使您的端点更难维护。您不再知道客户端将使用哪种方法来传递参数。
          • 老实说,这实际上是这种方法的主要优点之一,不必知道字段来自何处。上面的 ExpressData 类充当了一个桥梁,允许您模块化您的业务逻辑,将其从 express 控制器路由中移开,即您没有将 'req.query'、'req.body' 烘焙到您的代码中,这也使得您的业​​务代码易于测试,完全在 express 之外。
          【解决方案8】:
          const express = require('express')
          const bodyParser = require('body-parser')
          const { usersNdJobs, userByJob, addUser , addUserToCompany } = require ('./db/db.js')
          
          const app = express()
          app.set('view engine', 'pug')
          app.use(express.static('public'))
          app.use(bodyParser.urlencoded({ extended: false }))
          app.use(bodyParser.json())
          
          app.get('/', (req, res) => {
            usersNdJobs()
              .then((users) => {
                res.render('users', { users })
              })
              .catch(console.error)
          })
          
          app.get('/api/company/users', (req, res) => {
            const companyname = req.query.companyName
            console.log(companyname)
            userByJob(companyname)
              .then((users) => {
                res.render('job', { users })
              }).catch(console.error)
          })
          
          app.post('/api/users/add', (req, res) => {
            const userName = req.body.userName
            const jobName = req.body.jobName
            console.log("user name = "+userName+", job name : "+jobName)
            addUser(userName, jobName)
              .then((result) => {
                res.status(200).json(result)
              })
              .catch((error) => {
                res.status(404).json({ 'message': error.toString() })
              })
          })
          app.post('/users/add', (request, response) => {
            const { userName, job } = request.body
            addTeam(userName, job)
            .then((user) => {
              response.status(200).json({
                "userName": user.name,
                "city": user.job
              })
            .catch((err) => {
              request.status(400).json({"message": err})
            })
          })
          
          app.post('/api/user/company/add', (req, res) => {
            const userName = req.body.userName
            const companyName = req.body.companyName
            console.log(userName, companyName)
            addUserToCompany(userName, companyName)
            .then((result) => {
              res.json(result)
            })
            .catch(console.error)
          })
          
          app.get('/api/company/user', (req, res) => {
           const companyname = req.query.companyName
           console.log(companyname)
           userByJob(companyname)
           .then((users) => {
             res.render('jobs', { users })
           })
          })
          
          app.listen(3000, () =>
            console.log('Example app listening on port 3000!')
          )
          

          【讨论】:

          • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation would greatly improve its long-term value 通过展示为什么这是一个很好的解决问题的方法,并将使其对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
          【解决方案9】:

          您可以简单地使用req.query 获取查询参数:

          app.get('/', (req, res) => {
              let color1 = req.query.color1
              let color2 = req.query.color2
          })
          

          url 模块提供用于 URL 解析和解析的实用程序。不使用 Express 的 URL 解析:

          const url = require('url');
          const queryString = require('querystring');
          
          let rawUrl = 'https://stackoverflow.com/?page=2&size=3';
          
          let parsedUrl = url.parse(rawUrl);
          let parse = queryString.parse(parsedUrl.query);
          
          // parse = { page: '2', size: '3' }
          

          另一种方式:

          const url = require('url');
          
          app.get('/', (req, res) => {
            const queryObject = url.parse(req.url,true).query;
          });
          

          url.parse(req.url,true).query 返回 { color1: 'red', color2: 'green' }.
          url.parse(req.url,true).host 返回 'localhost:8080'.
          url.parse(req.url,true).search 返回 '?color1=red&color2=green'。

          【讨论】:

            【解决方案10】:

            只需使用app.get

            app.get('/some/page/here', (req, res) => {
                console.log(req.query.color) // Your color value will be displayed
            })
            

            你可以在 expressjs.com 文档 api 上看到它: http://expressjs.com/en/api.html

            【讨论】:

              猜你喜欢
              • 2010-09-29
              • 2015-03-11
              • 1970-01-01
              • 2018-03-10
              • 2016-04-22
              • 2011-09-17
              • 1970-01-01
              • 2019-05-25
              相关资源
              最近更新 更多