为什么 javaScript 中的 "append" 方法不返回数组?



这里是一个API调用,它需要一些值来返回一组特定的产品,

问题

  • "category_slug"必须是一个数组,但由于某些原因,API说它不是。这里有什么问题

const url = new URL(
"https://someApi/products"
);

let params = {
"limit": "10",
"page": "1",
"category_slug": ["shoes"]
};
// "limit" is "how many products in on one page".
// "page" is the fetched page with the specific "limited" products.
//issue
// "category_slug" is a specific products category, this has to be an array but for 
//  some reason, the API says it's not. what is the problem here?

Object.keys(params)
.forEach(key => url.searchParams.append(key, params[key]));
//here I'm appending the specific value in {params} to the URL.

let headers = {
"Accept": "application/json",
"Content-Type": "application/json",
};


fetch(url, {
method: "GET",
headers: headers,
})
.then(response => response.json())
.then(json => console.log(json));

看,你对URLSearchParams这样美丽的东西期望太少,同时又期望太多。

太少了,因为通常你可以将整个params对象传递到它的构造函数中,而不会在keysforEach等上浪费时间…

const url = new URL('https://example.com/');
const params = {
limit: 10,
page: 1
};
url.search = new URLSearchParams(params); // yes, that easy
console.log(url.toString()); 
// https://example.com/?limit=10&page=1

太多了,因为URLSearchParams不是为处理数组而设计的。当附加的元素是一个数组时,它只是字符串化的:

const url = new URL('https://example.com/');
const params = {
slug: [1, 2, 3]
};
url.search = new URLSearchParams(params);
console.log(url); // https://example.com/?slug=1%2C2%2C3

在这种情况下,slugparam得到了分配给它的1,2,3([1, 2, 3].toString()的结果((并且所有的逗号都是url编码的-用%2C序列代替(。

您的API可能真的可以使用它,但它期望数组参数以以下格式传递的可能性很大:

https://example.com/?slug=1&slug=2&slug=3

然而,如果API期望传递数组参数,并将[]附加到每个键,则即使这样也可能不起作用,如下所示:

https://example.com/?slug[]=1&slug[]=2&slug[]=3

因此,您必须检查您的API(仅通过观察水晶球很难调试这些东西,您知道…(,将其风味考虑在内,并单独处理您的项目。例如,

const url = new URL('https://example.com/');
const params = {
limit: 10,
page: 1
};
url.search = new URLSearchParams(params);
const slugs = [1, 2, 3];
url.search += ['', ...slugs.map(
slug => `category_slug[]=${encodeURIComponent(slug)}`)].join('&');
console.log(url.toString());

最新更新