我需要创buildurl来获取哪个接受数组,如何在node.js /从请求中提取数组?

我需要创buildurl来获取哪个接受数组,如何在node.js /从请求中提取数组? 我需要传递数组的名称,这些参数需要从Person返回

model. /api/person # here I need to pass which fields I want to see but to be generic. 

您可以用百分比编码来编码数组,只是“覆盖”一个字段,正式连接这些值。

 app.get('/test', function(req,res){ console.log(req.query.array); res.send(200); }); localhost:3000/test?array=a&array=b&array=c 

该查询将打印['a','b','c']

一种select是使用JSON格式。

 http://server/url?array=["foo","bar"] 

服务器端

 var arr = JSON.parse(req.query.array); 

或者你自己的格式

 http://server/url?array=foo,bar 

服务器端

 var arr = req.query.array.split(','); 

当查询参数在请求URL中多次重复时,Express会将查询参数显示为一个数组:

 app.get('/', function(req, res, next) { console.log(req.query.a) res.send(200) } GET /?a=x&a=y&a=2: // query.a is ['x', 'y', 'z'] 

其他方法同样适用于req.body。

您可以传递由斜线分隔的数组元素 – GET / api / person / foo / bar / …

将路线定义为'/api/person/(:arr)*'

req.params.arr将有第一个参数。 req.params[0]将剩下的string。 你用这两个分割并创build一个数组。

 app.get('/api/person/(:arr)*', function(req, res) { var params = [req.params.arr].concat(req.params[0].split('/').slice(1)); ... }); GET /api/person/foo params = ["foo"] GET /api/person/foo/bar params = ["foo", "bar"] 

如果你想从urlparameter passing一个数组,你需要遵循下面的例子:

url示例:

 https://website.com/example?myarray[]=136129&myarray[]=137794&myarray[]=137792 

从快速检索:

 console.log(req.query.myarray) [ '136129', '137794', '137792' ] 

使用下一个代码:

 app.use('/', (req, res) => { console.log(req.query, typeof req.query.foo, Array.isArray(req.query.foo)); res.send('done'); }); 

在后端,你有两个标准的方法。 对于下一个请求:

  1. /?富= 1&富= 2
  2. /?FOO [] = 1&FOO [] = 2

您的NodeJS后端将接收下一个查询对象:

  1. {foo:['1','2']}'object'true
  2. {foo:['1','2']}'object'true

所以,你可以用你想要的方式。 我的build议? 第二个 ,为什么? 因为如果你期望一个数组,而你只传递一个值,那么选项1将把它解释为一个常规值(string),而不是一个数组。

[我说我们有两个标准,不好,URL没有标准,这是自始至终存在的两种常用方法。 每个Web服务器都像Apache,JBoss,Nginx等一样。