What is the correct way to connect an authorization header to an Ajax request?

I have an ajax GET request that I run in the knockout code section, where I need to set the authorization header.

My preference usually relates to jQuery reduction methods:

$.getJSON("/api/business", function (allData) { var mappedOrgs = $.map(allData, function (item) { return new Business(item) }); self.businesses(mappedOrgs); }); 

This is fine on its own without any authorization requirements, but if I need to enable the carrier token, I tried the longer way:

 var token = sessionStorage.getItem(tokenKey); var headers = {}; if (token) { headers.Authorization = 'Bearer ' + token; } $.ajax({ type: 'GET', url: '/api/business', headers: headers }).done(function (data) { var mappedOrgs = $.map(data, function (item) { return new Business(item) }); self.businesses(mappedOrgs); }).fail(function () { console.error('api call failed'); }); 

Even trying to force a problem to start using the $ .ajaxSend () method does not produce any results.

 $(document).ajaxSend(function (event, xhr, settings) { var token = sessionStorage.getItem(tokenKey); var headers = {}; if (token) { console.info("Found token. Attaching to headers."); headers.Authorization = 'Bearer ' + token; settings.headers = headers; //console.info(headers); } }); 

So what do I not notice? I check every request in Fiddler and the Auth header is never attached. Obviously, this is the right way to do this, but somewhere I missed some step. Any help was appreciated.

+5
source share
1 answer

i use the following:

 function getListData(url) { var d = new $.Deferred(); cfg.apiLoad(); $.ajax({ url: baseUrl + url, type: 'GET', headers: { "x-access-token": secure.getToken(), "x-access-finger": finger.getFinger() }, dataType: 'json' }).fail(function(a, b, c) { cfg.failError(c); d.reject(c); }).done(function (r) { cfg.apiDone(r); d.resolve(r.ListResults); }); return d.promise(); } 

you can add as many extra headers you want, ignore cfg. stuff, but it's in a network file, as in write-once, use everything with getListData('/api/Name/Endpoint').then(function(r){ '// do something});

it solves any problems with the need to repeat, etc. and works like a charm. my API returns the same model for any results

+3
source

All Articles