javascript - 自定义配置导致的奇怪 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 引起的。
如果我config
从中取出window.fetch
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
未给定的路径:
- 三元进入虚假案例
headers
获得一个条目content-type: undefined
- 请求添加了此标头
- 请求被 api 拒绝,因为它包含一个内容类型标头(可能包含字符串
'undefined'
)
解决方案:这里不要使用三元,而是用 , 代替它if
,以摆脱undefined
条目。另外:阅读 javascript 对象中空值、未定义值和“拥有自己的属性”之间的差异
推荐阅读
- javascript - 如何使用 Google OAuth2 REST API 获取“撤销”请求的成功/失败回调?
- c# - 如何在弹出窗口内的主窗口上移动图像
- c++ - C++ std::map 键作为对象向量导致错误:运算符 __surrogate_func':找不到匹配的重载函数
- c# - 有没有办法以递归方式列出所有使用更改方法的类?
- r - R:获取发生唯一行的所有日期并将其存储在变量中
- firebase - Firebase 集合到 ReorderableListView
- docker - Docker mkdir C:: 权限被拒绝。/ 包含本地卷名的无效字符,仅允许“[a-zA-Z0-9][a-zA-Z0-9_.-]”
- reactjs - 为什么 React 不能识别传递给另一个组件的函数?
- c# - 在 Visual Studio 2019 for C# 上安装 JetEntityFrameWorkProvider
- r - 如何将数据集中的两个变量放在 R 中堆叠的条形图上