【问题标题】:Problem with CORS policy, when making a request to https://newsapi.org [duplicate]向 https://newsapi.org 发出请求时,CORS 政策出现问题 [重复]
【发布时间】:2020-09-09 02:22:24
【问题描述】:

我一直在我的网站上运行新闻 api,并通过将文件拖到网络浏览器中在我的计算机上进行测试,网址会显示为 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);
  });

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

【问题讨论】:

  • 您找到解决此问题的方法了吗?我也同时开始经历这种情况。 cors-anywhere cors 代理似乎对我不起作用。
  • 代理工作了一段时间,但现在我收到426 (Upgrade Required) 错误,不知道是什么原因造成的
  • 我遇到了同样的问题,发现 NewsApi 不再免费,只能在开发模式下工作,所以在 localhost 上没问题,但通过后端部署时就不行了....我花了一段时间才弄清楚,我绞尽脑汁,构建代理并尝试了很多东西......现在我认为解决它的唯一方法是构建自己的节点快速服务器。

标签: javascript cors


【解决方案1】:

您需要一个 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);
  });

【讨论】:

  • 在使用代理运行 URL 时,我在控制台中收到 401 (Unauthorized)
  • 您是否指定了所有必需的参数,包括 api 密钥?
  • 抱歉,我的 API 密钥错误,因此出现 401 (Unauthorized) 错误。使用正确的密钥,它可以工作!谢谢
【解决方案2】:

这是需要https://newsapi.org配置的东西。 这是他们的网站,通过 CORS,他们可以传达允许哪些网站嵌入其内容的方式和方式。大多数现代浏览器都遵循这些限制。

您最好联系他们的支持,或查看帐户设置,也许您需要使用一些令牌或在某处列出您的网站。

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

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 2018-10-21
    • 2022-06-17
    • 2019-05-08
    • 2022-12-11
    • 1970-01-01
    • 2015-10-07
    • 2020-12-23
    • 1970-01-01
    相关资源
    最近更新 更多