erwin erwin - 7 months ago 229
Javascript Question

ajaxSetup (beforeSend not working

after login to remote aPI server, and getting an access_token, I try to set the authorization header for all subsequent ajax calls :

.done(function (result) {
console.log("GOT AUTHORIZATION");
amplify.store( "tokens", { access_token: result.access_token, refresh_token: result.refresh_token, token_type: result.token_type, expires_in: result.expires_in });
var authorization = 'Bearer ' + amplify.store( "tokens" ).access_token;
console.log(authorization);

$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', authorization);
}
});


on console I can see :

GOT AUTHORIZATION login.js:34
Bearer 6b7578772fbb4178793100651f2234de840237fe


but none of subsequent ajax calls get the correct header set :

https://macmini.local:8000/Categories?_=1381758170726


cannot succeed as no access_token is found in the header ( server console ..)

{ code: 400,
error: 'invalid_request',
error_description: 'The access token was not found',stack: undefined }
saveAccessToken: 6b7578772fbb4178793100651f2234de840237fe, client_id: 1234567890, user_id: 1


I tried to modify the header inside the ajax call wo any success

Answer

Updated Answer

As of jQuery 1.5 .ajax supports headers property

$.ajax({
    url: "http://fiddle.jshell.net/favicon.png",
    headers: {
        'Authorization': authorization
    }
})
.done(function( data ) {
    if ( console && console.log ) {
        console.log( "Sample of data:", data.slice( 0, 100 ) );
    }
});

Notes: the authorization variable should be set somewhere before this call


Old Answer

$(function(){
    $.ajaxSetup({
        beforeSend: function(xhr) {
                 xhr.setRequestHeader('Authorization', authorization);
             }
    });
});

For the ajaxSetup to work you need to call it in the document.ready.

Comments