基本授权的ajax set headers不起作用

时间:2015-01-06 07:26:41

标签: jquery ajax http cors basic-authentication

这是我的代码,我想请求跨域网址使用基于基本授权的API。

但它不起作用。请求标头中没有显示授权信息。

$(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'Authorization': "Basic amlhemhc6SUxvdmVAkYXk="),
            'Content-Type': 'application/json;charset=utf-8'
        }
    });
    var request = $.ajax({
        url: "http:localhost:8080/query",
        type: "POST",
        data: '{"sql":"select count(*) from summary"}',
        dataType: "json"
    });
    request.done(function (msg) {
        alert(msg);
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});
enter image description here

2 个答案:

答案 0 :(得分:0)

尝试将以下回调添加到$.ajax()

var request = $.ajax({
        url: "http:localhost:8080/query",
        type: "POST",
        data: '{"sql":"select count(*) from summary"}',
        dataType: "jsonp",
        processData: 'false',
        xhrFields: {
              withCredentials: 'true'
        },
        crossDomain: 'true'
    });

答案 1 :(得分:0)

你的ajax看起来应该是这样的,如果它仍然不起作用那么你可以查看我关于CARS here的帖子,看看你面临的问题

ajaxOpts = {
        url:"https://"+server_name+"/post_link/",
        crossDomain:true,
        xhrFields: {withCredentials:true},
        type:'POST',
        data: jQuery('#some_form').serialize(),//or your data
        dataType:'json',
        success: {
            //do something
        },
        error: {
            //do something
        },
    };
    jQuery.ajax(ajaxOpts);

希望有所帮助