由自定义配置引起的奇怪的CORS问题 [英] weird CORS problem caused by custom config for fetch

查看:49
本文介绍了由自定义配置引起的奇怪的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中为 fetch 方法编写了一个小包装(我很清楚像Axios这样的库可以做同样的事情).我是从博客帖子中得到的想法

I was writing a little wrapper for fetch method in JavaScript (I am very aware of libs like Axios that can do the same thing). I got the idea from a blog post

我的代码如下

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无法提取,我认为这是由CORS引起的.

However, I encountered TypeError Failed to fetch which I believed is caused by 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问题...

The problem would be gone. Not sure which part exactly triggered this CORS problem...

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

推荐答案

按照 data 未提供路径:

  1. 三元陷入虚假情况
  2. headers 获得一个条目 content-type:undefined
  3. 请求将添加此标头
  4. 请求被api拒绝,因为它包含一个内容类型的标头(可能其中包含字符串'undefined')
  1. the ternary goes into the false case
  2. headers gets an entry content-type: undefined
  3. the request gets this header added
  4. request is rejected by api because it contains a content-type header (probably with the string 'undefined' in it)

解决方案:不要在此处使用三元数,而将其替换为 if ,以摆脱 undefined 条目.另外:读取空的,未定义的值与具有自己的属性"之间的差异.在javascript对象中

Solution: Dont use a ternary here, and replace it with an if, to get rid of the undefined entry. Also: read up on differences between null, undefined values and "has own property" in javascript objects

这篇关于由自定义配置引起的奇怪的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆