【问题标题】:Multiple GET parameter with ExpressExpress 的多个 GET 参数
【发布时间】:2017-04-19 11:20:36
【问题描述】:

我是 Node.js 和 Express 的新手, 我一直在做一个 RESTful API 项目,我正在尝试在 URL 中发送一个带有多个参数的 GET 请求:

这是我的路线:

/centers/:longitude/:latitude

这是我尝试调用它的方式:

/centers?logitude=23.08&latitude=12.12

我也试过了

/centers/23.08/12.12

它最终会走这条路线:

/centers/

那么我写端点的方式错了吗?还是我要求的方式?

【问题讨论】:

标签: node.js rest express


【解决方案1】:

您没有正确理解 Express 中路由定义的工作原理。

这样的路由定义:

/centers/:longitude/:latitude

表示它需要这样的 URL:

/centers/23.08/12.12

当您形成这样的 URL 时:

/centers?longitude=23.08&latitude=12.12

您正在使用查询参数(? 之后的param=value 对)。要访问这些,请参阅此问题/答案:How to access the GET parameters after "?" in Express?

为此,您可以为"/centers" 创建一个路由,然后访问req.query.longitudereq.query.latitude 以访问这些特定的查询参数。

【讨论】:

    【解决方案2】:

    这样试试

    var express = require('express');
    var app = express();
    var port = process.env.PORT || 8080;
    app.get('/centers/:log/:lat',function(req,res)
           {
    res.json({ log: req.params.log,
              lat: req.params.lat });
    
    });
    app.listen(port);
    console.log('Server started! At http://localhost:' + port);
    

    现在试试这样的网址http://localhost:8080/centers/55/55

    【讨论】:

    • 如何在单条路线中做到这一点? = /v2/search/:query&:author
    【解决方案3】:

    在路由器中定义url参数更容易。

    示例网址:http://www.example.com/api/users/3&0

    在 routes.js 中

    router.get('/api/users/:id&:pending', function (req, res) {
      console.log(req.params.id);
      console.log(req.params.pending);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 2012-10-27
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多