Ziko
Ziko

Reputation: 971

Ajax HTTP request interceptor, adding a header value after upon promise.resolve is not working

I'm trying to parse the authorization header in my HTTP requests via the ajax interceptor

$.ajaxSetup({
  beforeSend: function (xhr) {
    oauth.getCurrentToken().then((token) => {
      console.log(token); // gets logged for all my requests
      xhr.setRequestHeader('x-my-custom-header2', 'test2'); // doesn't work

    });
    xhr.setRequestHeader('x-my-custom-header', 'test1'); // work
  }
});

However, I can see that x-my-custom-header is getting added to my request, while x-my-custom-header2 is not.

Provisional headers are shown
Accept: */*
Referer: http://localhost:3000/
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
x-my-custom-header: test1

oauth.getCurrentToken() is basically a service that I have and it would resolve a token object after retrieving it from the localStorage.

The reason why I need to do getCurrentToken() before parsing it is that because the value may change from time to time so I need to always parse the latest token

Upvotes: 0

Views: 1699

Answers (1)

charlietfl
charlietfl

Reputation: 171669

The problem is beforeSend is synchronous so the promise then() won't fire before request gets sent

You probably need to create your own ajax service function so you can resolve getCurrentToken() before the request options are created

Something like:

function doAjax(url, data, type = 'get') {    
  return oauth.getCurrentToken().then((token) => {
    return $.ajax({
      url,
      data,
      type,
      beforeSend: (xhr) => xhr.setRequestHeader('x-my-custom-header2', token);
    });    
  });
}

// usage
doAjax('somePath', {foo:'bar'}, 'post').then(res=> console.log(res))

Upvotes: 1

Related Questions