I have an ajax GET request I'm firing in a section of Knockout code where I need to ensure the Authorization header is set.
My preference is usually to go with the jQuery shorthand methods like so:
$.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 auth requirement but if I need to include the bearer token, I've been trying the more long-winded 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 the issue through the $.ajaxSend() method doesn't yield 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 am I overlooking? I'm checking each request in Fiddler and the Auth header is never attached. There's obviously a right way to do this but I'm missing a step somewhere. Any help appreciated.
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 on there that you wish, ignore the cfg. stuff, but this is in a network file, as in write once, use everywere withgetListData('/api/Name/Endpoint').then(function(r){ '// do something});
this then solves any issues with having to repeat etc and works like a charm. my API returns the same model back for any type of results
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With