加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax – 为什么我的跨域POST请求被OPTIONS请求预检?

发布时间:2020-12-16 02:50:42 所属栏目:百科 来源:网络整理
导读:根据Mozilla开发人员中心 HTTP access control的文章,如果请求的Content-Type是application / x-www-form-urlencoded,跨站点POST请求可以“简单” – 即不需要预检. 我在Firefox中没有得到这种行为,我根本不理解为什么会这样.这是我的设置代码: function ma
根据Mozilla开发人员中心 HTTP access control的文章,如果请求的Content-Type是application / x-www-form-urlencoded,跨站点POST请求可以“简单” – 即不需要预检.

我在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"

这是Fiddler中的预检OPTIONS请求(请注意Access-Control-Request-Method:POST标头,即使我指定了一个所谓的安全Content-Type而且没有自定义标头):

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 bug.它最终得到修复FF4b6: https://bugzilla.mozilla.org/show_bug.cgi?id=588920

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读