首页 > 解决方案 > 自定义配置导致的奇怪 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

标签: javascripthtmlhttpcors

解决方案


遵循data未给定的路径:

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

解决方案:这里不要使用三元,而是用 , 代替它if,以摆脱undefined条目。另外:阅读 javascript 对象中空值、未定义值和“拥有自己的属性”之间的差异


推荐阅读