我一直在我的网站上运行新闻 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);
});
Run Code Online (Sandbox Code Playgroud)
当我在本地运行 API 时,该 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 代理
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);
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7948 次 |
| 最近记录: |