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

时间:2020-05-22 09:20:58

标签: javascript cors

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

很长一段时间,一切正常,但是最终,API停止工作,并且在控制台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'添加到提取中,但是不适用于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);
  });

当我在本地file:///C:上运行该API时,它也停止工作,它显示的错误与Github页面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页面上以及当我在PC上本地运行时显示信息?

2 个答案:

答案 0 :(得分:4)

您需要CORS代理

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);
  });

答案 1 :(得分:0)

这是https://newsapi.org需要配置的内容。 这是他们的网站,并与CORS交流如何允许以及哪些网站嵌入其内容。而且大多数现代浏览器都遵循这些限制。

最好的选择是与他们的支持人员联系,或者查看帐户设置,也许您需要使用一些令牌或在某个位置列出您的网站。

除了联系https://newsapi.org并要求他们更改许可/ CORS之外,我想您可以做一个代理服务器来复制其内容,但这可能会破坏使用条款。