0
首先,我是使用API的新手。簡單的API調用(CORS)不起作用
我正在嘗試對不同的域(天氣服務)進行最基本的API調用,而不是我自己的客戶端。其中,我遇到了CORS問題,沒有正確的頭文件等等,所以我試着通過crossorigin.me(通過我的代碼中的URL顯而易見)引導調用來制定解決方法。
(這不是代碼,但僅僅是問題 - 向下滾動代碼)然而,我的代碼目前導致...
console.log(status); //returns 0
console.log(statusText); //returns an empty string
這是一個完整的代碼。
function createCORSRequest(method, url) {
xhr = new XMLHttpRequest();
//I work in Chrome, so I only included withCredentials, not accounting for other browsers
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
}
xhr.send();
console.log(xhr.status); //returns 0
console.log(xhr.statusText); //returns empty string
}
createCORSRequest("GET", "https://crossorigin.me/https://www.metaweather.com/api/location/2459115");
如果你訪問該網站直接,https://crossorigin.me/https://www.metaweather.com/api/location/2459115,我得到這個消息:原產地:頭是必需的。在控制檯中,它給出了狀態碼403 - 但我讀到只有服務器可以控制/訪問標題,而且我(編碼器)不能。
您只是在請求發送之前嘗試讀取狀態。你必須等待迴應。 – Quentin
「但我讀過,只有服務器可以控制/訪問標題」 - HTTP消息有標題。 HTTP請求具有標題。 HTTP響應具有標題。服務器抱怨你的HTTP請求沒有包含「Origin」標頭。這是因爲您沒有使用XMLHttpRequest發送它。 – Quentin
@行2上的Quentin,我將xhr定義爲XMLHttpRequest。爲什麼它不是XMLHttpRequest呢?非常感謝你 – thesystem