带Express的多个GET参数

Sha*_*rma 5 rest node.js express

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

这是我的路线:

/centers/:longitude/:latitude
Run Code Online (Sandbox Code Playgroud)

以下是我试图称之为:

/centers?logitude=23.08&latitude=12.12
Run Code Online (Sandbox Code Playgroud)

而且我也试过了

/centers/23.08/12.12
Run Code Online (Sandbox Code Playgroud)

它最终会走这条路线:

/centers/
Run Code Online (Sandbox Code Playgroud)

我编写端点的方式是错误的吗?还是我要求它的方式?

jfr*_*d00 8

您没有正确理解路径定义在Express中的工作原理.

像这样的路由定义:

/centers/:longitude/:latitude
Run Code Online (Sandbox Code Playgroud)

意味着它期待这样的URL:

/centers/23.08/12.12
Run Code Online (Sandbox Code Playgroud)

当您形成这样的URL时:

/centers?longitude=23.08&latitude=12.12
Run Code Online (Sandbox Code Playgroud)

您正在使用查询参数(param=value后面的对?).要访问这些,请参阅此问题/答案:如何在"?"之后访问GET参数 在快递?

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


Adi*_*iii 6

像这样尝试

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);
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明