12

I want to add custom headers (Bearer token) to each http call in a ASP.Net Web Form application.

Using the recommendations in the following links, I added the code to send added headers to the server to no avail.

How to intercept all http requests including form submits

and

How to alter the headers of a Request?

<script>
    (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);
    })();
</script>

And

<script>
    (function() { 
        (function (send) {
            XMLHttpRequest.prototype.send = function (data) {
                console.log("Adding header");
                this.setRequestHeader("X-Hello", "There");
                send.call(this, data);
            };
        })(XMLHttpRequest.prototype.send);
    })();
</script>

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.

The long solution using the service worker failed on:

return Promise.resolve(new Request(data.url, data));

"Failed to construct 'Request': Cannot construct a Request with a Request whose mode is 'navigate' and a non-empty RequestInit."

4 Answers 4

10

Try this:-

XMLHttpRequest.prototype.open = (function(open) {
  return function(method,url,async) {
    open.apply(this,arguments);
    this.setRequestHeader('customHeader1', 'someValue');
    this.setRequestHeader('customHeader2', 'someOtherValue');
    };
})(XMLHttpRequest.prototype.open);
Sign up to request clarification or add additional context in comments.

1 Comment

While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive-feedback/upvotes from users, when the code is explained.
6

One way to do this would be to use a service worker. However this method is not supported by all browsers, so watch your audience. With a service worker, you would intercept all the fetch requests that go through the browser. however browsers will only allow you to send custom headers for urls related to the current origin. With that in mind, here's a code sample.

//This is the fetch event listener
self.addEventListener("fetch", (event) => {
    var currentUrl = new URL(event.request.url);
    if (currentUrl.origin === location.origin){
        var newRequest = new Request(event.request, {
            mode: "cors",
            credentials: "same-origin",
            headers: {
                YOUR_CUSTOM_HEADER_NAME: YOUR_CUSTOM_HEADER_VALUE,
            }
        });
        event.respondWith(fetch(newRequest));
    }
    else {
        event.respondWith(fetch(event.request));
    }
});

Also if you use a constant, variable to store the headers value and name, the browser will take the name of the variable(in lower case) as the header name(not it's value).

2 Comments

you can put the variable name in brackets { [foo]: var} to use the value inside of the variable, instead of foo as the key.
This will work for client running in browser right? But can you share a way to track outgoing http calls similar to in server side? For example from express.js ?
1

You need to instantiate XMLHttpRequest to use it.

var x = new XMLHttpRequest();
x.open("GET","http://some.url");
x.setRequestHeader("X-Hello","There");
x.send();

You wouldn't use Request directly... that is created internally by the modern fetch(..) API.

fetch("http://some.url",{ method:"GET", headers: { "X-Hello": "There" }})
.then(function onRes(res){
   if (res && res.ok) {
      // ..
   }
});

Comments

0

You can try using a service worker. Listen for any fetch events and just modify the outgoing request.

self.addEventListener('fetch', event => {
  event.respondWith(
    (async function() {
      // Get the current user token
      const token = await getToken();

      // Clone the request to modify headers
      const modifiedRequest = new Request(event.request, {
        headers: new Headers({
          ...Object.fromEntries(event.request.headers),
          'Authorization': `Bearer ${token}`
        })
      });

      return fetch(modifiedRequest);
    })()
  );
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.