根据Mozilla开发中心的说法 HTTP访问控制 文章,跨站点邮政请求可以“简单” - 即不需要预覆盖 - 如果请求的内容类型为 application/x-www-form-urlencoded.

我没有在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);
        }
    }
}

这是我正在使用的服务器:

// thanks to http://saltybeagle.com/cors/ for having this demo endpoint:
var URL = "http://ucommbieber.unl.edu/CORS/cors.php";

现在,如果我做一个简单的帖子请求 - 将数据发送为 application/x-www-form-urlencoded 在上面的代码中 - 该请求在Firefox中预先闪烁,并带有选项请求。它没有在镀铬中预击。在运行此之前,打开提琴手,亲自看:

makeXDomainRequest(URL, "POST", "name=foobar");
// alerts "Response! Hello CORS [...] You sent a POST request. Your name is foobar"

这是提琴手中的飞行前选项请求(请注意 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中的错误,还是我做错了什么?谢谢!

有帮助吗?

解决方案

事实证明,这确实是一个Firefox错误。它最终被修复了FF4B6: https://bugzilla.mozilla.org/show_bug.cgi?id=588920

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top