5

I have the following function that set up the headers of my AJAX requests:

self.authenticate = function () {
    self.token = sessionStorage.getItem(tokenKey);
    var headers = {};

    if (self.token) {
        headers.Authorization = 'Bearer ' + self.token;
        $.ajaxSetup({
            headers: headers
        });
    }
}

But this is not working, when I check the headers in the developers toll (F12) or in Fiddler, I don't see the custon header there, but when I set the header on the request and not through ajaxSetup it works perfectly.

The authenticate functions is being called in the Layout page:

$(document).ready(function () {
     var avm = new AuthenticationViewModel();
     avm.authenticate();
});

And self.token is not null.

For example, for this request:

self.getUsers = function (callback) {
    $.get("../API/Users/GetUsers/",callback);
}

these are the headers: enter image description here

What am I missing?

user3378165
  • 6,546
  • 17
  • 62
  • 101
  • I have to ask the obvious question. Are you actually calling the authenticate function anywhere? – Reinstate Monica Cellio Jun 12 '17 at 07:31
  • @Archer Please see my edited question. – user3378165 Jun 12 '17 at 07:38
  • Set a breakpoint at `avm.authenticate();` and your `$.get("../API/Users/GetUsers/");` and make sure that: 1. Authentication is actually called. 2. Authentication is called **before** get requests. – Yeldar Kurmangaliyev Jun 14 '17 at 09:05
  • @YeldarKurmangaliyev I did so, the answer for both is- yes. – user3378165 Jun 14 '17 at 09:40
  • Before `if (self.token) {` , type `console.log(self.token)` and let me know what you are getting – Sagar V Jun 14 '17 at 10:14
  • @SagarV : `LSHBs5movtDDo5fR5kzpQDCr8C88stGN-XMH-gL0UZobAL-WmutQ0F5KX0Y-f6TcXUeCgRmXCuhDMuX26_c3LpOcUIZVigzGMNHc4OyaIe82ALdgNJZaeyYToto5aMSvDpcAIqyjvcnm9y-wJQWFl9pNcprf2TAf2etBIHrI6mPQ4RraiQgNWPnv2dxuDTd0B54V8wUD_NN0Bkw9cCyfPFZteef2cm9XdW2OiJHfR5hCF6zr2DxBsjA4aplRgCrBx5AmuYvIn5KrFV36G4RmOcPH5d6fQH920CIDuATCQJKzpSxwPlHEVGVhSjRWzUeSgm7wdcYWj18F9H0NpyyFxb51VIKKZ0d4f-rtugCgqHeJMOpIrVnmCqo73t15o6Tc-F-7U-B49w5VdYjN2CmneW9w8risBObEATvjkND486Vx2Vnwc5hXn_4rNsoQo-nPi4wXtA_vSUr8iPWt2tDtm5V5s0dU71VW9x4ThB7zd_efd6dQA3Y3VqunnozOoaT10ps9` – user3378165 Jun 14 '17 at 11:02
  • Please check the value of `headers`. Is it really an object containing `Authorization` ? – Sagar V Jun 14 '17 at 11:08
  • @SagarV `Object {Authorization: "Bearer LSHBs5movtDDo5fR5kzpQDCr8C88stGN-XMH-gL0UZo…tm5V5s0dU71VW9x4ThB7zd_efd6dQA3Y3VqunnozOoaT10ps9"}` – user3378165 Jun 14 '17 at 11:16
  • are you calling it in document.ready ? – Sagar V Jun 14 '17 at 11:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/146645/discussion-between-sagar-v-and-user3378165). – Sagar V Jun 14 '17 at 11:37
  • Have you confirmed if you reach the inside of the `if` statement by putting a console.log in there? Also, what happens if you copy/paste this `$.ajaxSetup()` code just before your first instance of calling `$.ajax()`? Does it work then? – therobinkim Jun 17 '17 at 07:22
  • What is `AuthenticationViewModel`? – Mr_Perfect Jun 17 '17 at 09:32
  • @therobinkim The answer for both questions is Yes. – user3378165 Jun 18 '17 at 05:55

3 Answers3

7

$.ajaxSetup sets default values for future Ajax requests.

Its use is not recommended as suggested in the JQuery documentation.

Anyways, as it sets the default values for future calls it must execute before all ajax calls that depends on those default values. For example, if you didn't mention the url of the call, the default url that configured in the $ajaxSetup will be the url of the call. If the call you made depends on those defaults then this code

self.authenticate = function () {
    self.token = sessionStorage.getItem(tokenKey);
    var headers = {};
    if (self.token) {
        headers.Authorization = 'Bearer ' + self.token;
        $.ajaxSetup({
            headers: headers
        });
    }
} 

must execute before the below call is made.

self.getUsers = function () {
    $.get("../API/Users/GetUsers/");
}

Now check this

***************Plunker for answer****************

In that plunker go to network tab in the developer console by pressing F12 and check the headers in those calls made by $.ajax() and $.get()

In the plunker I observed that(Points to be read),

  • If the call is $.ajax() then the headers are showing and the url of the call is the url that is mentioned in the $.ajaxSetup
  • If the call is $.get() then the headers are not showing and the url of the call is the plunker url means in your case it will be http://MySite/ etc.

$.ajax() is the most configurable one, where you get fine grained control over HTTP headers and such. You're also able to get direct access to the XHR-object using this method. Slightly more fine-grained error-handling is also provided. Can therefore be more complicated and often unecessary, but sometimes very useful. You have to deal with the returned data yourself with a callback.

$.get() is just a shorthand for $.ajax() but abstracts some of the configurations away, setting reasonable default values for what it hides from you. Returns the data to a callback. It only allows GET-requests so is accompanied by the $.post() function for similar abstraction, only for POST

For more info

DIFFERENCE BETWEEN $.ajax() and $.get(), $.post()

Just test the plunker if you want.


Image of $.ajax() call

enter image description here


Image of $.get() call

enter image description here

Hence, If you want to set the headers just use $.ajax() instead of $.get()

Hope this helps :)

Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62
3

I ended up moving:

$(document).ready(function () {
     var avm = new AuthenticationViewModel();
     avm.authenticate();
});

From the Layout page to the page itself and that solved the issue.

AuthenticationViewModel-Creates a new AuthenticationViewModel for logging users in and getting their info.

user1012506
  • 2,048
  • 1
  • 26
  • 45
user3378165
  • 6,546
  • 17
  • 62
  • 101
-1

the syntax should be like

headers: { 'x-my-custom-header': 'some value' }

ie; you may rewrite your functions as

self.authenticate = function () {
    self.token = sessionStorage.getItem(tokenKey);

    if (self.token) {
       //headers.Authorization = 'Bearer ' + self.token;
       $.ajaxSetup({
           headers: {Authorization:  'Bearer ' + self.token}
       });
   }
}
Jacob Nelson
  • 2,370
  • 23
  • 35