問題描述
我一直在使用 CORS,遇到了以下問題.客戶端抱怨沒有 'Access-Control-Allow-Origin' 標頭存在,而 它們存在,并且 客戶端發出實際的 POST 請求 并且 收到 200強>.
I've been working with CORS and encountered the following issue. Client complains about no 'Access-Control-Allow-Origin' header is present, while they are present, and client make the actual POST request and receives 200.
function initializeXMLHttpRequest(url) { //the code that initialize the xhr
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
//set headers
for (var key in headers) {
if (headers.hasOwnProperty(key)) { //filter out inherited properties
xhr.setRequestHeader(key,headers[key]);
}
}
return xhr;
}
在 Chrome 中
chrome 控制臺日志
chrome console log
Chrome 選項請求
Chrome OPTIONS request
Chrome POST 請求
Chrome POST request
在火狐中
Firefox 控制臺日志
Firefox Console Log
Firefox 選項請求
Firefox OPTIONS request
Firefox POST 請求
Firefox POST request
推薦答案
簡而言之:訪問控制標頭(例如 Access-Control-Allow-Origin
)需要同時出現以響應 OPTIONS 和實際的POST.
In short: Access control headers (e.g. Access-Control-Allow-Origin
) need to present in response for both OPTIONS and actual POST.
工作流程:
Client 使用這些 HTTP 訪問標頭發出 OPTIONS 請求.(例如
Origin、Access-Control-Request-Method、Access-Control-Request-Headers
)
Client make OPTIONS request with those HTTP access headers. (e.g.
Origin, Access-Control-Request-Method, Access-Control-Request-Headers
)
服務器響應這些訪問控制標頭,允許訪問.(例如 Access-Control-Allow-Origin、Access-Control-Expose-Headers、Access-Control-Max-Age、Access-Control-Allow-Credentials、Access-Control-Allow-Methods、Access-Control-Allow-標題
)
Server respond with those access control headers, allowing access. (e.g. Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Allow-Credentials, Access-Control-Allow-Methods, Access-Control-Allow-Headers
)
客戶端使用數據發出 POST 請求.
Client makes POST request with data.
服務器響應 POST.如果服務器響應中不存在 Access-Control-Allow-Origin
標頭.雖然 POST 成功并在 network 選項卡中顯示 200 狀態碼,但 xhr.status
為 0 并且會觸發 xhr.onerror
.瀏覽器會顯示錯誤消息.
Server respond to POST. If Access-Control-Allow-Origin
header is NOT present in the server response. Although the POST is successful and shows 200 status code in network tab, xhr.status
is 0 and xhr.onerror
will be triggered. And browser would show up the error message.
標題參考:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
這篇關于Javascript CORS - 不存在“Access-Control-Allow-Origin"標頭的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!