gpt4 book ai didi

node.js - NodeJS : Request Library - What is the Proper way to use userQueryString?

转载 作者:行者123 更新时间:2023-12-02 19:43:33 24 4
gpt4 key购买 nike

Within the Request Documentation它使用以下内容记录设置“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.

我正在使用的 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);

当我在选项“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"

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

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

感谢您的帮助!

最佳答案

文档中的措辞有点误导。

当它说使用querystring时,这意味着request模块将使用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

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

http://testyurl.com/?foo=bar&bar=foo&arr%5B0%5D=foo&arr%5B1%5D=bar&arr%5B2%5D=etc

因为 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

关于node.js - NodeJS : Request Library - What is the Proper way to use userQueryString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com