title: Adding custom headers in Javascript for all http requests
body: <p>I want to add custom headers (Bearer token) to each http call in a ASP.Net Web Form application.</p>
  
  <p>Using the recommendations in the following links, I added the code to send added headers to the server to no avail.</p>
  
  <p><a href="https://stackoverflow.com/questions/43813770/how-to-intercept-all-http-requests-including-form-submits">How to intercept all http requests including form submits</a></p>
  
  <p>and</p>
  
  <p><a href="https://stackoverflow.com/questions/35420980/how-to-alter-the-headers-of-a-request/35421644#35421644">How to alter the headers of a Request?</a></p>
  
  <pre><code>&lt;script&gt;
      (function() { 
          (function (open) {
              XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
                  console.log("Adding header");
                  open.call(this, method, url, async, user, password);
                  this.setRequestHeader("X-Hello", "There " + new Date());
              };
          })(XMLHttpRequest.prototype.open);
      })();
  &lt;/script&gt;
  </code></pre>
  
  <p>And</p>
  
  <pre><code>&lt;script&gt;
      (function() { 
          (function (send) {
              XMLHttpRequest.prototype.send = function (data) {
                  console.log("Adding header");
                  this.setRequestHeader("X-Hello", "There");
                  send.call(this, data);
              };
          })(XMLHttpRequest.prototype.send);
      })();
  &lt;/script&gt;
  </code></pre>
  
  <p>I understand that the solution is supposed to work only for the POSTs (but it doesn't.)  I do see the console.log for every post, yet the header, "X-Hello" never shows on the server side.</p>
  
  <p>The long solution using the service worker failed on:</p>
  
  <pre><code>return Promise.resolve(new Request(data.url, data));
  </code></pre>
  
  <p>"Failed to construct 'Request': Cannot construct a Request with a Request whose mode is 'navigate' and a non-empty RequestInit."</p>