我正在尝试使用window.fetch发出一个"GET“请求,并且我需要传入一个参数,该参数接受整个数组作为值。例如,请求url应如下所示。
'https://someapi/production?moves=[]'
我有以下代码段,它以400请求结束,因为数组的计算结果为空
let url = new URL('https://someapi/production');
let params = {moves: []};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
console.log(url);
fetch(url.href)
.then(res => res.json())
.then(val => {
console.log(val);
});
在检查之后,url.href看起来像这样
https://someapi/production?moves=
在我想要的地方
https://someapi/production?moves=[]
对如何实现这一点有什么建议吗?
发布于 2018-08-20 12:37:04
因为url.searchParams.append(key, params[key])
的第二个参数不是字符串URLSearchParams.append
will result in the value being stringified。我假设这是通过对其调用Array.prototype.toString()
方法来实现的,该方法省略了数组括号。
因此,您需要将一些方括号连接到该字符串上,或者调用一个不同的方法(如注释中提到的JSON.stringify
)来保留方括号。
https://stackoverflow.com/questions/51923866
复制相似问题