获取 Api 获取参数

Fetch Api get params

我正在尝试使用 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=[]

关于如何实现这一点有什么建议吗?

因为url.searchParams.append(key, params[key])的第二个参数不是字符串,URLSearchParams.append will result in the value being stringified。我假设这是通过调用 Array.prototype.toString() 方法来实现的,它省略了数组括号。

因此,您需要将一些括号连接到该字符串上,或者调用其他方法(如评论中提到的 JSON.stringify)来保留括号。