首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当向https://newsapi.org发出请求时,CORS策略出现问题

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

Stack Overflow用户
提问于 2020-05-22 09:20:58
回答 2查看 6.6K关注 0票数 2

我一直在我的网站上运行新闻api,并在我的电脑上测试通过将文件拖到网络浏览器中,url会像file:///C:那样出现。然后,我会将任何更改上传到我的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();不兼容

我的功能如下:

代码语言:javascript
运行
复制
  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上本地运行它时?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-22 09:27:01

你需要一个CORS代理

代码语言:javascript
运行
复制
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);
  });

票数 5
EN

Stack Overflow用户

发布于 2020-05-22 09:26:53

这是需要https://newsapi.org配置的东西。这是他们的网站,并与CORS沟通如何和哪些网站允许嵌入他们的内容。大多数现代浏览器都遵循这些限制。

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61951713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档