Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

javascript - cross-origin 'Authorization'-header with jquery.ajax()

I'm trying to send a cross-origin domain and adding a custom 'Authorization'-header. Please see the code below.

Error:

XMLHttpRequest cannot load {url}. Request header field Authorization is not allowed by Access-Control-Allow-Headers.

function loadJson(from, to) {
    $.ajax({
        //this is a 'cross-origin' domain
        url : "http://localhost:2180/api/index.php",
        dataType : 'json',
        data : { handler : "statistic", from : from, to : to
        },
        beforeSend : setHeader,
        success : function(data) {
            alert("success");
        },
        error : function(jqXHR, textStatus, errorThrown) {
            alert("error");
        }
    });
}

function getToken() {
    var cookie = Cookie.getCookie(cookieName);
    var auth = jQuery.parseJSON(cookie);
    var token = "Token " + auth.id + ":" + auth.key;
}

function setHeader(xhr) {
    xhr.setRequestHeader('Authorization', getToken());
}

I also tried:

headers : { 'Authorization' : getToken() },

in the ajax request.

Could it be that the jquery-ajax framework is blocking cross-origin Authentification? How can I fix this?

Update:

By the way: is there a safer method to store the auth.key on client-side then in a cookie? getToken() will be replaced with a more complex method, hashing the body, date,etc.

question from:https://stackoverflow.com/questions/9559947/cross-origin-authorization-header-with-jquery-ajax

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is an example of making a CORS request. If you have access to the server (which I assume you do since this is a request to localhost), you will need to add CORS-specific response headers. The simplest thing to do is to add the following response headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization

Your server also needs to be configured to respond to HTTP OPTIONS requests. You can learn more about making CORS requests here: http://www.html5rocks.com/en/tutorials/cors/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...