我需要为将接受数组的 get 创建 url,如何在 node.js/express 中从请求中提取数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22080770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:56:12  来源:igfitidea点击:

I need to create url for get which is going to accept array, how in node.js/express extract array from request?

node.jsexpress

提问by PaolaJ.

I need to create url for get which is going to accept array, how in node.js/express extract array from request ? I need to pass array with names which parametes I need to back from Person

我需要为将接受数组的 get 创建 url,如何在 node.js/express 中从请求中提取数组?我需要传递带有我需要从 Person 返回的参数名称的数组

model.

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

回答by Kevin Reilly

One option is using a JSON format.

一种选择是使用 JSON 格式。

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

Server side

服务器端

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

Or your own format

或者你自己的格式

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

Server side

服务器端

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

回答by durum

You can encode an array in percent encodingjust "overwriting" a field, formally concatenating the values.

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

app.get('/test', function(req,res){
    console.log(req.query.array);
    res.send(200);
});




localhost:3000/test?array=a&array=b&array=c

This query will print ['a','b','c'].

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

回答by Muhammad Fawwaz Orabi

Express exposes the query parameter as an array when it is repeated more than once in the request URL:

当查询参数在请求 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']

Same applies for req.body in other methods.

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

回答by Jose Mato

Using next code:

使用下一个代码:

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

On backend, you have two standard approaches. For next requests:

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

  1. /?foo=1&foo=2
  2. /?foo[]=1&foo[]=2
  1. /?foo=1&foo=2
  2. /?foo[]=1&foo[]=2

your NodeJS backend will receive next query object:

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

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

So, you can choose the way you want to. My recommendation is the second one, why? If you're expect an array and you just pass a single value, then option one will interpret it as a regular value (string) and no an array.

所以,你可以选择你想要的方式。我的建议是第二个,为什么?如果您需要一个数组并且您只传递一个值,那么选项一会将其解释为常规值(字符串)而不是数组。

[I said we have two standards and is not ok, there is no standard for arrays in urls, these are two common ways that exist. Each web server does it in it's own way like Apache, JBoss, Nginx, etc]

[我说我们有两个标准是不行的,urls中的数组没有标准,这是两种常见的存在方式。每个 Web 服务器都以自己的方式运行,如 Apache、JBoss、Nginx 等]

回答by Dimitri

If you want to pass an array from url parameters, you need to follow the bellow example:

如果要从 url 参数传递数组,则需要按照以下示例进行操作:

Url example:

网址示例:

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

To retrieve it from express:

要从 express 中检索它:

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

回答by Ryan

Express has a tool to check if your path will match the route you are creating : Express.js route tester.

Express 有一个工具可以检查您的路径是否与您正在创建的路由匹配:Express.js 路由测试器

As Jose Mato says you have to decide how to structure your url:

正如何塞·马托所说,您必须决定如何构建您的网址:

  1. ?foo=1&foo=2
  2. ?foo[]=1&foo[]=2
  1. ?foo=1&foo=2
  2. ?foo[]=1&foo[]=2

The http request should look like this, if you chose method 1:

如果您选择方法 1,则 http 请求应如下所示:

http://baseurl/api/?foo=1&foo=2

http://baseurl/api/?foo=1&foo=2

Your route should have this logic:

您的路线应该具有以下逻辑:

app.get('/api/:person', (req, res) => {
    /*This will create an object that you can iterate over.*/
    for (let foo of req.params.foo) {
      /*Do some logic here*/
    }
});

回答by Remario

Here use this, '%2C' is the HTML encoding character for a comma.

这里使用这个,'%2C' 是逗号的 HTML 编码字符。

jsonToQueryString: function (data) {
   return Object.keys(data).map((key) => {
        if (Array.isArray(data[key])) {
            return encodeURIComponent(`${key}=${data[key].map((item) => item).join('%2C')}`);
        }
        return encodeURIComponent(`${key}=${data[key]}`);
    }).join('&');
}

To access the query params

访问查询参数

const names = decodeURIComponent(req.query.query_param_name);
const resultSplit = names.split(',');

回答by palanik

You can pass array elements separated by slashes - GET /api/person/foo/bar/...

您可以传递由斜杠分隔的数组元素 - GET /api/person/foo/bar/...

Define your route as '/api/person/(:arr)*'

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

req.params.arrwill have the first parameter. req.params[0]will have the rest as string. You split and create an array with these two.

req.params.arr将有第一个参数。 req.params[0]将剩下的作为字符串。您将这两个拆分并创建一个数组。

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"]

...

...