【发布时间】: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