简体   繁体   English

在 Javascript 中为所有 http 请求添加自定义标头

[英]Adding custom headers in Javascript for all http requests

I want to add custom headers (Bearer token) to each http call in a ASP.Net Web Form application.我想向 ASP.Net Web 窗体应用程序中的每个 http 调用添加自定义标头(不记名令牌)。

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 如何拦截包括表单提交在内的所有http请求

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.我知道该解决方案应该只适用于 POST(但它不适用。)我确实看到了每个帖子的 console.log,但标题“X-Hello”从未显示在服务器端。

The long solution using the service worker failed on:使用 Service Worker 的长解决方案失败了:

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." “无法构建‘请求’:无法使用模式为‘导航’的请求和非空的 RequestInit 构建请求。”

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.使用 Service Worker,您将拦截所有通过浏览器的 fetch 请求。 however browsers will only allow you to send custom headers for urls related to the current origin.但是浏览器只允许您发送与当前来源相关的 url 的自定义标头。 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).此外,如果您使用常量变量来存储标头值和名称,浏览器会将变量的名称(小写)作为标头名称(不是它的值)。

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

You need to instantiate XMLHttpRequest to use it .您需要实例化XMLHttpRequest才能使用它

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 .您不会直接使用Request ......这是由现代fetch(..) API在内部创建的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM