由fetch的自定义配置引起的奇怪的CORS问题



我正在用JavaScript为fetch方法编写一个小包装器(我非常清楚Axios这样的库也可以做同样的事情(。我从的一篇博客文章中得到了这个想法

我的代码看起来像这个

async function apiCall(
endpoint,
{ data, headers: customHeaders, ...customConfig } = {}
) {
console.log("endpoint", endpoint);
const config = {
method: data ? "POST" : "GET",
body: data ? JSON.stringify(data) : undefined,
headers: {
"content-type": data ? "application/json" : undefined,
...customHeaders
},
...customConfig
};
return window.fetch(endpoint, config).then(async (response) => {
if (response.ok) {
return response.json();
} else {
// By default, window.fetch will only reject a promise if the actual request itself failed (network error), not if it returned a "Client error response".
const error = await response
.json()
.catch(() => new Error("invalid json"));
return Promise.reject(error);
}
});
}
export function requestMovies(query) {
const endpoint = `${apiULR}?apikey=${API_KEY}&s=${encodeURIComponent(query)}`;
return apiCall(endpoint);
}

然而,我遇到了TypeError Failed to fetch,我认为它是由CORS引起的。

如果我像中那样从window.fetch中取出config

async function apiCall(
endpoint,
{ data, headers: customHeaders, ...customConfig } = {}
) {
return window.fetch(endpoint).then(async (response) => {
if (response.ok) {
return response.json();
} else {
// By default, window.fetch will only reject a promise if the actual request itself failed (network error), not if it returned a "Client error response".
const error = await response
.json()
.catch(() => new Error("invalid json"));
return Promise.reject(error);
}
});
}

问题会解决的。不确定是哪个部分引发了这个CORS问题。。。

这是一个现场演示:https://codesandbox.io/s/charming-saha-4c2bh?file=/src/index.js

遵循data未给定的路径:

  1. 三元进入错误情况
  2. headers得到一个条目content-type: undefined
  3. 请求会添加此标头
  4. 请求被api拒绝,因为它包含一个内容类型标头(可能包含字符串'undefined'(

解决方案:此处不要使用三元,并将其替换为if,以消除undefined条目。此外:读取null、未定义值和"之间的差异;拥有自己的财产";在javascript对象中

最新更新