根據Mozilla Developer Center HTTP access control文章,如果請求的內容類型爲application/x-www-form-urlencoded
,則跨站點POST請求可以是「簡單的」 - 即不需要預檢。爲什麼我的跨域POST請求被OPTIONS請求預檢?
我沒有得到這種行爲在Firefox中,我不理解爲什麼這樣。這是我的設置代碼:
function makeXDomainRequest(url, method, data) {
var req =
typeof XDomainRequest !== "undefined" ?
new XDomainRequest() : new XMLHttpRequest();
req.open(method || "GET", url, true);
if (typeof req.onload !== "undefined") {
req.onload = onResponseLoad;
req.onerror = onRequestError;
} else {
req.onreadystatechange = onRequestStateChange;
}
if (data && typeof req.setRequestHeader === "function") {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
} else {
// no way to set Content-Type req header in IE's XDomainRequest:
// http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
}
req.send(data || null);
}
function onResponseLoad() {
alert("Response!\n" + this.responseText);
}
function onRequestError(args) {
alert("Error!");
}
function onRequestStateChange() {
if (this.readyState === 4) {
if (this.status === 200) {
onResponseLoad.apply(this);
} else {
onRequestError.apply(this);
}
}
}
這裏就是我ping服務器:
// thanks to http://saltybeagle.com/cors/ for having this demo endpoint:
var URL = "http://ucommbieber.unl.edu/CORS/cors.php";
現在,如果我做一個簡單的POST請求 - 在上面的代碼發送作爲application/x-www-form-urlencoded
數據 - 請求在Firefox中通過OPTIONS請求進行預檢。在Chrome中未預先指定。運行此之前打開Fiddler看到自己:
makeXDomainRequest(URL, "POST", "name=foobar");
// alerts "Response! Hello CORS [...] You sent a POST request. Your name is foobar"
這裏是預檢選項提琴手要求(即使我指定的所謂安全Content-Type和沒有自定義頁眉注意到Access-Control-Request-Method: POST
頭):
OPTIONS http://ucommbieber.unl.edu/CORS/cors.php HTTP/1.1
Host: ucommbieber.unl.edu
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://localhost
Access-Control-Request-Method: POST
發生了什麼事?這是Firefox中的錯誤,還是我做錯了什麼?謝謝!