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;
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.
source share