$ .ajaxSetup not working

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

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

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

But this does not work, when I check the headers in the developer tables (F12) or in Fiddler, I do not see the custon header, but when I set the header to the request, and not through ajaxSetupit it works fine.

On the Layout page, the authenticatefollowing functions are called :

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

And self.tokennot 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?

+4
source share
3 answers

I ended up moving:

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

From page Layoutto page itself and which solved the problem.

+2
source

$. ajaxSetup Ajax.

, JQuery.

, , ajax, . , url , url, $ajaxSetup, url . ,

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

.

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

*************** Plunker ********* *******

plunker , F12 , $.ajax() $.get()

, (, ),

  • $.ajax(), , url - url, $.ajaxSetup
  • $.get(), , url - plunker url, http://MySite/ ..

$.ajax() , HTTP- .. XHR . . , . .

$.get() $.ajax(), , , . . GET $.post() , POST

$.ajax() $.get(), $.post()

, .


$.ajax()

enter image description here


$.get()

enter image description here

, headers, $.ajax() $.get()

, :)

+4

the syntax should look like

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

t; you can 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}
       });
   }
}
-1
source

Source: https://habr.com/ru/post/1679028/


All Articles