向 https://newsapi.org 发出请求时,CORS 政策出现问题

2022-01-15 00:00:00 cors javascript

我一直在我的网站上运行新闻 api 并通过将文件拖到网络浏览器中在我的计算机上进行测试,网址会显示为 file:///C:.然后我会将任何更改上传到我的 GitHub 存储库并在 Github 页面 https://name.github.io/repository/ 上运行它.

I have been running news api on my website and testing in on my computer by dragging the file into the web browser, the url would show up like that file:///C:. Then I would upload any changes to my GitHub repository and run it on Github pages https://name.github.io/repository/.

长期以来一切正常,但最终,API 停止工作,控制台中出现错误 Access to fetch at 'https://newsapi.org/v2/everything?xx' from originhttps://name.github.io"已被 CORS 策略阻止:请求的资源上不存在Access-Control-Allow-Origin"标头.如果不透明的响应满足您的需求,请将请求的模式设置为no-cors"以获取禁用 CORS 的资源.

Everything was working fine for a long time, but eventually, the API stopped working and error showed up in the console Access to fetch at 'https://newsapi.org/v2/everything?xx' from origin 'https://name.github.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我尝试将 mode: 'no-cors' 添加到 fetch 中,但它不适用于 return response.json();

I have tried to add mode: 'no-cors' to the fetch, but it didn't work with return response.json();

我的函数如下所示:

  const url = 'https://newsapi.org/v2/everything?' +
    'qInTitle=""&' +
    `from=` +
    'language=en&' +
    'apiKey=';
  const req = new Request(url);

  fetch(req).then(function(response) {
    return response.json();
  }).then(function(news) {
    newsLoop(news);
  });

当我在本地运行它时,API 也停止工作 file:///C:,它显示与 Github 页面上的错误类似的错误 Access to fetch at 'https://newsapi.org/v2/everything?xx' from origin 'null' 已被 CORS 策略阻止:请求的资源上不存在Access-Control-Allow-Origin"标头.如果不透明的响应满足您的需求,请将请求的模式设置为no-cors"以获取禁用 CORS 的资源.

The API stopped working also when I run it locally file:///C:, it displays a similar error to the one on Github pages Access to fetch at 'https://newsapi.org/v2/everything?xx' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我该如何处理,以便 API 会在 Github 页面上显示信息,以及当我在我的电脑上本地运行它时?

How I can deal with it, so the API would display information on Github pages and when I run it locally on my pc?

推荐答案

你需要一个 CORS 代理

You need a CORS proxy

const proxyUrl = "https://cors-anywhere.herokuapp.com/"
const qInTitle = "";
const from = "";
const apiKey = "";
const url = `${proxyUrl}https://newsapi.org/v2/everything?qInTitle=${qInTitle}&from=${from}language=en&apiKey=${apiKey}`;
const request = new Request(url);

fetch(request)
  .then(response => response.json())
  .then((news) => {
    console.log(news);
  })
  .catch(error => {
    console.log(error);
  });

相关文章