問題描述
我一直在我的網站上運行新聞 api 并通過將文件拖到網絡瀏覽器中在我的計算機上進行測試,網址會顯示為 file:///C:
.然后我會將任何更改上傳到我的 GitHub 存儲庫并在 Github 頁面 https://name.github.io/repository/
上運行它.
I have been running news api on my website and testing in on my computer by dragging the file into the web browser, the url would show up like that file:///C:
. Then I would upload any changes to my GitHub repository and run it on Github pages https://name.github.io/repository/
.
長期以來一切正常,但最終,API 停止工作,控制臺中出現錯誤 Access to fetch at 'https://newsapi.org/v2/everything?xx' from originhttps://name.github.io"已被 CORS 策略阻止:請求的資源上不存在Access-Control-Allow-Origin"標頭.如果不透明的響應滿足您的需求,請將請求的模式設置為no-cors"以獲取禁用 CORS 的資源.
Everything was working fine for a long time, but eventually, the API stopped working and error showed up in the console 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();
I have tried to add mode: 'no-cors'
to the fetch, but it didn't work with 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' 已被 CORS 策略阻止:請求的資源上不存在Access-Control-Allow-Origin"標頭.如果不透明的響應滿足您的需求,請將請求的模式設置為no-cors"以獲取禁用 CORS 的資源.
The API stopped working also when I run it locally file:///C:
, it displays a similar error to the one on Github pages 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 頁面上顯示信息,以及當我在我的電腦上本地運行它時?
How I can deal with it, so the API would display information on Github pages and when I run it locally on my pc?
推薦答案
你需要一個 CORS 代理
You need a CORS proxy
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);
});
這篇關于向 https://newsapi.org 發出請求時,CORS 政策出現問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!