jquery - What is the correct way to attach an Authorization header to an Ajax request? -


i have ajax request i'm firing in section of knockout code need ensure authorization header set.

my preference go jquery shorthand methods so:

$.getjson("/api/business", function (alldata) {     var mappedorgs = $.map(alldata, function (item) { return new business(item) });     self.businesses(mappedorgs); }); 

this fine on own without auth requirement if need include bearer token, i've been trying 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 force issue through $.ajaxsend() method doesn't yield results.

$(document).ajaxsend(function (event, xhr, settings) {     var token = sessionstorage.getitem(tokenkey);     var headers = {};     if (token) {         console.info("found token. attaching headers.");         headers.authorization = 'bearer ' + token;         settings.headers = headers;         //console.info(headers);     } }); 

so overlooking? i'm checking each request in fiddler , auth header never attached. there's right way i'm missing step somewhere. appreciated.

i use 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 many headers on there wish, ignore cfg. stuff, in network file, in write once, use everywere with
getlistdata('/api/name/endpoint').then(function(r){ '// something});

this solves issues having repeat etc , works charm. api returns same model type of results


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -