繁体   English   中英

获取已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

[英]fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

我正在使用来自https://www.football-data.org 的api 制作这个网络应用程序

当我为网络制作样板时,我在控制台中收到此错误

错误图像

const ENPOINT_JER = `${BASE_URL}competition/2002/standings`;
const ENPOINT_BEL = `${BASE_URL}competition/2003/standings`;
const ENPOINT_ING = `${BASE_URL}competition/2021/standings`;
const ENPOINT_SPA = `${BASE_URL}competition/2014/standings`;
const ENPOINT_PER = `${BASE_URL}competition/2015/standings`;

const fetchAPI = (url) => {
  return fetch(url, {
    headers: {
      "X-Auth-Token": API_KEY,
    },
  })
    .then((res) => {
      if (res.status !== 200) {
        console.log(`Error: ${res.status}`);
        return Promise.reject(new Error(res.statusText));
      } else {
        return Promise.resolve(res);
      }
    })
    .then((res) => res.json())
    .catch((err) => {
      console.log(err);
    });
};

function getStandingJer() {
  if ("caches" in window) {
    caches.match(ENPOINT_JER).then(function (response) {
      if (response) {
        response.json().then(function (data) {
          console.log("Competition Data: " + data);
          showStanding(data);
        });
      }
    });
  }

  fetchAPI(ENPOINT_JER)
    .then((data) => {
      showStanding(data);
    })
    .catch((error) => {
      console.log(error);
    });
}

我已经创建了 API_KEY 变量

有一些浏览器插件可以在您的应用程序开发时抑制 cors:https ://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

如果您使用 node 和 express,有一个 cors 中间件包可以提供帮助,但设置仍然很棘手。 首先使用npm install cors导入模块;

then in your server.js file:
const   express =   require('express')
const   app =   express();

然后在回调之前将 cors() 作为 arg 添加到端点。 在这本书中的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM