如何解决 Netlify 中的 cors 问题

cyb*_*Ann 5 cors reactjs netlify

我在 Netlify 上使用了一个 React 应用程序 6 个月,没有出现任何问题。从 .com 更改为 .app 后,我的网站开始收到 CORS 错误消息:

从来源“ https://jovial-mccarthy-f17fcd.netlify.app ”访问“ https://newsapi.org/v2/everything?q=bitcoin&from=2020-5-27&sortBy=publishedAt&apiKey=xxx ”处的 XMLHttpRequest已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

当我在本地服务器上运行时,它运行良好,并且没有错误消息,但是当在 Netlify 上部署时,我收到上面的错误消息。

我已将 netlify.toml 文件添加到我的根文件夹中:

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

[[headers]]
  # Define which paths this specific [[headers]] block will cover.
  for = "/*"
    [headers.values]
    Access-Control-Allow-Origin = "*"
Run Code Online (Sandbox Code Playgroud)

但我仍然收到错误消息,并且 api 新闻数据被阻止显示在我的网站上。

我使用 axios 进行数据调用。

import axios from 'axios';

const API_URL = "https://newsapi.org/v2/everything?q=bitcoin&from=2020-5-27&sortBy=publishedAt&apiKey=1b823477c9864b7ebb4eb4e9d4148238";

//async function grabbing bitCoin data
export const getNews = async () => {
  const result = await axios.get(API_URL)
  .then(response => {
  console.log(response.data);
  return response.data.articles;
  });
  return(result);
}import axios from 'axios';

const API_URL = "https://newsapi.org/v2/everything?q=bitcoin&from=2020-5-27&sortBy=publishedAt&apiKey=xxx";

//async function grabbing bitCoin data
export const getNews = async () => {
  const result = await axios.get(API_URL)
  .then(response => {
  console.log(response.data);
  return response.data.articles;
  });
  return(result);
}
Run Code Online (Sandbox Code Playgroud)

我尝试了 Netilify 建议的不同方法,但我有点新手,不知道如何解决这个问题......

如何解决项目中的 CORS 问题?为什么用了 6 个月,现在出现了 CORS 问题?看来这是 Netlify 的问题,我需要以某种方式配置它。

谢谢!

归档时间:

查看次数:

6542 次

最近记录:

5 年,11 月 前