请求https://newsapi.org时存在CORS策略问题。
请求https://newsapi.org时存在CORS策略问题。
这个问题在此处已有答案:
我一直在我的网站上运行新闻API,并通过将文件拖到Web浏览器中在我的计算机上进行测试,网址看起来像这样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\'
到fetch,但它与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页面上显示信息,并在本地计算机上运行时也能工作?
这是需要由 https://newsapi.org 配置的内容。这是他们的网站,并且通过CORS通信,以确定哪些站点可以嵌入他们的内容,大多数现代浏览器都会遵循这些限制。
你最好联系他们的支持团队,或者查看账户设置,也许你需要使用某些令牌或将你的站点列在某个地方。
除了联系https://newsapi.org并要求他们提供许可证/CORS更改之外,我想你可以做一个代理服务器来复制他们的内容,但这可能会违反使用条款。
您需要一个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); });