在Javascript中为所有http请求添加自定义标头 [英] Adding custom headers in Javascript for all http requests

查看:1271
本文介绍了在Javascript中为所有http请求添加自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向ASP.Net Web窗体应用程序中的每个http调用添加自定义标头(承载令牌).

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.

如何拦截包括表单提交在内的所有http请求

如何更改请求的标头?

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

还有

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

我了解该解决方案仅适用于POST(但无效).我确实看到每个帖子的console.log,但服务器端从未显示标头"X-Hello"

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

无法构造'Request':无法使用模式为'navigate'且非空RequestInit的请求构造请求."

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

推荐答案

一种方法是使用服务工作者.但是,并非所有浏览器都支持此方法,因此请注意您的听众. 与服务工作者一起,您将拦截通过浏览器的所有提取请求.但是,浏览器仅允许您发送与当前来源相关的url的自定义标头.考虑到这一点,这是一个代码示例.

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

这篇关于在Javascript中为所有http请求添加自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆