我正在尝试使用window.fetch发出“ GET”请求,并且我需要传递一个将整个数组作为值的参数。例如,请求网址应如下所示
'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=[]
关于如何实现此目标的任何建议?
答案 0 :(得分:1)
因为url.searchParams.append(key, params[key])
的第二个参数不是字符串URLSearchParams.append
will result in the value being stringified。我以为是通过调用其上的Array.prototype.toString()
方法而忽略了数组括号。
因此,您需要将一些括号连接到该字符串上,或者调用其他方法(例如注释中提到的JSON.stringify
)来保留括号。