【问题标题】:Node.js: Difference between req.query[] and req.paramsNode.js:req.query[] 和 req.params 之间的区别
【发布时间】:2013-01-03 06:22:07
【问题描述】:

通过req.query[myParam]req.params.myParam 获取QUERY_STRING 参数有区别吗?如果是这样,我应该什么时候使用哪个?

【问题讨论】:

    标签: node.js query-string


    【解决方案1】:

    假设你已经这样定义你的路由名称:

    https://localhost:3000/user/:userId
    

    将会变成:

    https://localhost:3000/user/5896544
    

    在这里,如果您要打印: request.params

    {
    userId : 5896544
    }
    

    所以

    request.params.userId = 5896544
    

    所以 request.params 是一个包含命名路由属性的对象

    request.query 来自 URL 中的查询参数 例如:

    https://localhost:3000/user?userId=5896544 
    
    

    request.query

    {
    
    userId: 5896544
    
    }
    

    所以

    request.query.userId = 5896544
    
    

    【讨论】:

    • 很好的解释
    • 解释得很好!
    【解决方案2】:

    我只想补充一点,如果您来自axios,(GET/POST)您可以通过配置使用query/url params(使用req.query 读取):

    axios.post('/users', {...data}, {
      headers: {...anyHeaders},
      params: {uid: `${uid}`}
    })

    然后您通过路径使path/route variables(使用req.params 可读)可用:

    axios.get(`/users/${uid`}, {
      headers: {...anyHeaders}
    })

    我还要补充一点,用于在服务器上读取查询参数的名称必须与来自客户端的名称匹配。如果路径/路由的一部分可用(基本上是进行替换 - 有点像 react-router 的做法:/path/:variable),则路径变量的情况并非如此,因为路径变量可以在服务器上使用任何名称。

    【讨论】:

      【解决方案3】:

      我想提一个关于 req.query 的重要说明,因为目前我正在研究基于 req.query 的分页功能,并且我有一个有趣的示例要向您展示...

      例子:

      // Fetching patients from the database
      exports.getPatients = (req, res, next) => {
      
      const pageSize = +req.query.pageSize;
      const currentPage = +req.query.currentPage;
      
      const patientQuery = Patient.find();
      let fetchedPatients;
      
      // If pageSize and currentPage are not undefined (if they are both set and contain valid values)
      if(pageSize && currentPage) {
          /**
           * Construct two different queries 
           * - Fetch all patients 
           * - Adjusted one to only fetch a selected slice of patients for a given page
           */
          patientQuery
              /**
               * This means I will not retrieve all patients I find, but I will skip the first "n" patients
               * For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
               * 
               * Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
               * so I want to skip (7 * (2 - 1)) => 7 items
               */
              .skip(pageSize * (currentPage - 1))
      
              /**
               * Narrow dont the amound documents I retreive for the current page
               * Limits the amount of returned documents
               * 
               * For example: If I got 7 items per page, then I want to limit the query to only
               * return 7 items. 
               */
              .limit(pageSize);
      }
      patientQuery.then(documents => {
          res.status(200).json({
              message: 'Patients fetched successfully',
              patients: documents
          });
        });
      };
      

      你会注意到+req.query.pageSizereq.query.currentPage前面的标志

      为什么?如果你在这种情况下删除+,你会得到一个错误,并且会抛出该错误,因为我们将使用无效类型(错误消息'limit'字段必须是数字)。

      重要提示:默认情况下,如果您从这些查询参数中提取某些内容,它将始终为字符串,因为它来自 URL 并且被视为文本。

      如果我们需要处理数字,并将查询语句从文本转换为数字,我们可以简单地在语句前面添加一个加号。

      【讨论】:

        【解决方案4】:

        您现在应该可以使用点表示法访问查询了。

        如果你想访问,说你在/checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XX 收到一个GET 请求,并且你想获取所使用的查询

        var type = req.query.type,
            email = req.query.email,
            utm = {
             source: req.query.utm_source,
             campaign: req.query.utm_campaign
            };
        

        Params 用于接收请求的自定义参数,类似于(示例):

        router.get('/:userID/food/edit/:foodID', function(req, res){
         //sample GET request at '/xavg234/food/edit/jb3552'
        
         var userToFind = req.params.userID;//gets xavg234
         var foodToSearch = req.params.foodID;//gets jb3552
         User.findOne({'userid':userToFind}) //dummy code
             .then(function(user){...})
             .catch(function(err){console.log(err)});
        });
        

        【讨论】:

          【解决方案5】:

          req.params 包含路由参数(在 URL 的路径部分),req.query 包含 URL 查询参数(在 URL 中的 ? 之后)。

          您也可以使用req.param(name) 在这两个位置(以及req.body)查找参数,但此方法现在已弃用。

          【讨论】:

          • 啊,好的,谢谢,这两个都是 Express 提供的。以及我通过 req.body.myParam 访问的 POST 数据?
          • 对。使用哪一个取决于您要执行的操作。
          • 另请注意:“为清楚起见,应优先使用对 req.body、req.params 和 req.query 的直接访问 - 除非您真正接受来自每个对象的输入。” - 快递文件
          • req.param 现在已弃用。 Node 建议使用req.queryreq.params
          • 为什么要弃用它?如果我们使用 params 或 query 然后决定将其更改为另一个呢?
          【解决方案6】:

          鉴于这条路线

          app.get('/hi/:param1', function(req,res){} );
          

          并给出这个 URL http://www.google.com/hi/there?qs1=you&qs2=tube

          你将拥有:

          req.查询

          {
            qs1: 'you',
            qs2: 'tube'
          }
          

          req.参数

          {
            param1: 'there'
          }
          

          Express req.params >>

          【讨论】:

          • 如果我需要获取 /hi/ 怎么办?
          • 看看req.url or req.originalUrl or req._originalUrl,然后在/上拆分
          • 这应该是答案,简洁明了,容易上手,
          猜你喜欢
          • 2019-03-26
          • 1970-01-01
          • 2021-12-25
          • 2020-05-10
          • 2014-09-20
          • 2010-10-28
          • 2015-10-04
          • 2012-08-12
          • 2011-02-18
          相关资源
          最近更新 更多