【问题标题】:Fetch Api get paramsFetch Api 获取参数
【发布时间】:2018-08-20 12:37:04
【问题描述】:

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

关于如何实现这一点的任何建议?

【问题讨论】:

  • 这里有错字吗new URL('https://someapi/production) 缺少结束引号
  • JSON.stringify(params[key]) ?
  • @brk 对不起,这是我的错字

标签: javascript fetch fetch-api


【解决方案1】:

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

因此,您要么需要将一些括号连接到该字符串上,要么调用不同的方法(如 cmets 中提到的JSON.stringify)来保留括号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多