1

I have this code in my jquery code

$(document).ajaxError(function(event, xhr, settings) {
    var url = new URL(settings.url);
    if (url.pathname.toLowerCase().startsWith("/api/".toLowerCase()) && xhr.status === 401) {
        var new_access_token = getToken();
        // replace header value "Authorization" with "Bearer " + new_access_token
        // re-submit ajax request
    }
});

Does anyone know how to edit the request and re-send it?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

1 Answers1

0

Instead of tying into the ajaxError function, how do you feel about just handling the error right where you make the AJAX request? There is a built in error callback you can use, and that way you'd still have easy scope access to the original request so as to resend it.

const getToken = () => 'Bearer 123';

const sendRequestWithResend = (url, options) => {
  let existingErrorFunction = options.error;
  options.error= function(XMLHttpRequest, textStatus, errorThrown) {
    if(existingErrorFunction){
      existingErrorFunction(XMLHttpRequest, textStatus, errorThrown);
    }
    //resend request with header token, if header wasn't set
    if(options.headers && options.headers.Authorization){
      return; //token was already set
    }else{
      if(!options.headers){
        options.headers = {};
      }
      options.headers.Authorization = getToken();
      sendRequestWithResend(url,options);
    }
  }
  $.ajax(url,options);
}

sendRequestWithResend('https://notarealdomainforthisexample.com',{});

Here, I've created a wrapper function for your AJAX calls. It automatically adds an error handler (while preserving any existing error handling function) that retries the request (calling the same function recursively) with the bearer token (unless it already had a token -- important to prevent an infinite loop).

tmdesigned
  • 2,098
  • 2
  • 12
  • 20