NodeJS:请求库 - 使用 userQueryString 的正确方法是什么?

Dou*_*oug 2 node.js node-request

在请求文档中,它记录了设置“useQuerystring”,内容如下:

useQuerystring - if true, use querystring to stringify and parse querystrings, otherwise use qs (default: false). Set this option to true if you need arrays to be serialized as foo=bar&foo=baz instead of the default foo[0]=bar&foo[1]=baz.
Run Code Online (Sandbox Code Playgroud)

我正在使用的 API 需要向同一参数名称发送多个值;这个设置似乎表明可以在使用 useQueryString 时完成,但我似乎无法弄清楚在哪里/如何传递查询字符串,以便正确处理它以及以什么格式执行它。

例如,我在以下代码中尝试了多个不同位置的查询字符串:

let options = {
    uri: "https://api.mysite.com"[0],
    headers: {
        'Authorization': 'Bearer TOKEN_VALUE'
    },
    json: true,
    useQuerystring: true,
    querystring: "foo=bar&foo=baz",
    qs: "foo=bar&foo=baz",
    proxy: "http://localhost:8080",
    strictSSL: false,

};

request.get(options);
Run Code Online (Sandbox Code Playgroud)

当我在选项“querystring”中传递查询字符串时,它会忽略它(又名,它似乎是错误的位置)。当我把它放在“qs”的“正常”位置时;我最终得到发送到服务器的以下 URL:

"?0=f&1=o&2=o&3=%3D&4=b&5=a&6=r&7=%26&8=f&9=o&10=o&11=%3D&12=b&13=a&14=z"
Run Code Online (Sandbox Code Playgroud)

使用 useQuerystring 设置为 true 时传递查询字符串的正确方法是什么?

根据以下文件,它看起来没有改变查询字符串的位置,所以我认为它是 qs; 但如上所述,这不起作用: https ://github.com/request/request/blob/master/lib/querystring.js

感谢您的帮助!

小智 5

文档中的措辞有点误导。

当它说 use querystring时,这意味着请求模块将使用querystring模块将您的 qs 参数构建为查询字符串。或者您可以使用 querystring.parse(...) 将查询字符串解析为对象,然后将该对象传递给 qs 参数。

我相信这是您想要做的事情的正确用法:

const req = require('request');

const opts = {
    foo: 'bar',
    bar: 'foo',
    arr: ['foo', 'bar', 'etc']
};

const apiOptions = {
    uri: 'http://testyurl.com',
    headers: {},
    json: true,
    useQuerystring: true,
    qs: opts
};

req.get(apiOptions);

//This yields: http://testyurl.com/?foo=bar&bar=foo&arr=foo&arr=bar&arr=etc
Run Code Online (Sandbox Code Playgroud)

未能设置 useQuerystring: true 参数将产生像您所看到的奇怪的结果:

http://testyurl.com/?foo=bar&bar=foo&arr%5B0%5D=foo&arr%5B1%5D=bar&arr%5B2%5D=etc
Run Code Online (Sandbox Code Playgroud)

因为 request 试图转义 url 中的 arr[0]、arr[1] 和 arr[2]。

还有一个选择:

const opts = {
    foo: 'bar',
    bar: 'foo',
    arr: ['foo', 'bar', 'etc']
};

const querystring = require('querystring');
const uri = 'http://testyurl.com' + querystring.stringify(opts);

// yields: http://testyurl.comfoo=bar&bar=foo&arr=foo&arr=bar&arr=etc
Run Code Online (Sandbox Code Playgroud)