Reputation:
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
Upvotes: 9
Views: 28806
Reputation: 3804
I know this is an old question, but I came here from Google and thought other people searching the same thing should have a working solution. I have tried the suggested answer but it does not work for me.
A solution which solved my problem is to set header directly in xhr
object inside of $.ajaxSend
:
$(document).ajaxSend(function(ev, xhr, settings) {
xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem(AUTH_TOKEN)}`);
xhr.setRequestHeader('X-Marketplace', localStorage.getItem('marketplace'));
});
You should call it in the document.ready
for the ajaxSend
to work.
That similar question helped me.
Upvotes: 0
Reputation: 18823
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
$(function(){
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', authorization);
}
});
});
For the ajaxSetup
to work you need to call it in the document.ready.
Upvotes: 17