使用自定义标头发送纯ajax HTTP请求

时间:2013-12-16 11:59:40

标签: javascript jquery http-headers xmlhttprequest

我有一个现有的Java客户端,其中IOS和andriod开发人员准备了一个简单的基于http请求的应用程序。我正在尝试在HTML5应用程序中实现相同的功能。

现在面临的困难是在AJAX请求中发送自定义标头,例如使用加密登录详细信息进行授权。

我尝试在各种REST客户端上实现相同功能,并且能够在请求标头中发送“AUTHORIZATION:BASIC XXXXXX =”。并获得适当的json响应“

enter image description here

但如果我使用ajax调用尝试相同,则无法发送类似的请求标头。请求发送为OPTIONS而不是GET,并且授权标记不能正确地作为标题,而是作为“访问控制请求标题:授权”。

这是我试过的片段。

 <script>
    //$.ajaxSetup({ headers: { 'Authorization': 'Basic XXXXXXX='} })


    // get form data for POSTING       
    var vFD = new FormData(document.getElementById('upload_form'));
    var oXHR = new XMLHttpRequest();
    oXHR.open('POST', "https://123.123.123.123:229/");
    //oXHR.send(vFD);



    var body = 'Basic XXXXXXX=';
    var mUrl = "https://123.123.123.123:229/?json";
    var client = new XMLHttpRequest();
    client.open('GET', mUrl, true);
    client.withCredentials = true;
    client.crossDomain = true,

    client.setRequestHeader('Authorization', 'Basic XXXXXXX=');
    client.send(body);



    simpleHttpRequest();
    function simpleHttpRequest() {
        alert("calling ");

        var headers = {
            "Authorization": "Basic XXXXXXX="
        };
        $.ajaxSetup({ "headers": headers });
        $.ajaxSetup({ 'cache': false });
        $.ajax({
            type: "GET",
            withCredentials: true,
            //                data: {
            //                    address: 'http://www.google.com'
            //                },
            crossDomain: true,
            Headers: { "Authorization": "Basic XXXXXXX=" },
            dataType: "jsonp",
            url: mUrl,
            cache: false
        });
    }

    xhrToSend();
    function xhrToSend() {
        // Attempt to creat the XHR2 object
        var xhr;
        try {
            xhr = new XMLHttpRequest();
        } catch (e) {
            try {
                xhr = new XDomainRequest();
            } catch (e) {
                try {
                    xhr = new ActiveXObject('Msxml2.XMLHTTP');
                } catch (e) {
                    try {
                        xhr = new ActiveXObject('Microsoft.XMLHTTP');
                    } catch (e) {
                        statusField('\nYour browser is not' +
                    ' compatible with XHR2');
                    }
                }
            }
        }
        xhr.withCredentials = true;
        xhr.open('GET', mUrl, true);
        xhr.setRequestHeader("Authorization", "numberOfBLObsSent");
        xhr.send();
    };
</script>

所有不同的方式都失败了。请帮我。

提前致谢。

1 个答案:

答案 0 :(得分:1)

该问题与请求的跨域性质有关。当您创建包含自定义标头的跨域请求时,请求首先通过OPTIONS方法“预检”到服务器,并且服务器必须使用标头Access-Control-Allow-Headers: your-custom-header进行响应。收到后,ajax客户端将(自动)发出实际请求。

More on preflighted requests

相关问题