Adding custom headers in Javascript for all http requests

后端 未结 2 1782
悲哀的现实
悲哀的现实 2020-12-21 00:07

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 t

相关标签:
2条回答
  • 2020-12-21 00:29

    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) {
          // ..
       }
    });
    
    0 讨论(0)
  • 2020-12-21 00:49

    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).

    0 讨论(0)
提交回复
热议问题