Adding custom headers in Javascript for all http requests

后端 未结 2 1784
悲哀的现实
悲哀的现实 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) {
          // ..
       }
    });
    

提交回复
热议问题