我一直在我的网站上运行新闻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();
不兼容
我的功能如下:
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上本地运行它时?
发布于 2020-05-22 09:27:01
你需要一个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);
});
发布于 2020-05-22 09:26:53
这是需要https://newsapi.org配置的东西。这是他们的网站,并与CORS沟通如何和哪些网站允许嵌入他们的内容。大多数现代浏览器都遵循这些限制。
您最好是联系他们的支持,或查看帐户设置,也许您需要使用一些令牌或列出您的网站某处。
除了联系https://newsapi.org并要求他们更改许可证/ CORS之外,我想您还可以使用代理服务器复制它们的内容,但这可能会违反使用条款。
https://stackoverflow.com/questions/61951713
复制相似问题