Search code examples
javascriptauthenticationtokenintercept

How to replace header tokens in all requests with XMLHttpRequest in JavaScript?


The following code snippet updates the header information for each request.

   var open: any = XMLHttpRequest.prototype.open;

   XMLHttpRequest.prototype.open = function () {
      open.apply(this, [].slice.call(arguments));
      this.setRequestHeader('Authorization', `Bearer ${token}`);
   };

As a result, it merges the header token with the previous request token.

enter image description here

How can I prevent tokens from merging in the header? In fact, the new token will be overwritten.


Solution

  • enter image description here

    According to the existing document, rewriting the header in the interceptor is a wrong scenario This means that the script should not get to the point where the header needs to be rewritten I suggest checking most of the project to avoid sending unwanted headers

    But there is still a way (non-standard) Which somehow overwrited the header But other problems may arise

    var open = XMLHttpRequest.prototype.open;
    var send = XMLHttpRequest.prototype.send;
    var method = "";
    var url ="";
    XMLHttpRequest.prototype.open = function (_method,_url) {
    
    method = _method;
    url = _url;
    open.apply(this, [].slice.call(arguments)); 
    };
    
    XMLHttpRequest.prototype.send = function (data) {
    var xml2 = new XMLHttpRequest();
    xml2.open(method, url,true); 
    xml2.setRequestHeader('Authorization', "aaa");
    send.call(xml2, data);
    };

    enter image description here