【问题标题】:Adding custom headers in Javascript for all http requests在 Javascript 中为所有 http 请求添加自定义标头
【发布时间】:2019-09-25 13:14:56
【问题描述】:

我想为 ASP.Net Web 窗体应用程序中的每个 http 调用添加自定义标头(不记名令牌)。

使用以下链接中的建议,我添加了代码以将添加的标头发送到服务器,但无济于事。

How to intercept all http requests including form submits

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>

<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”从未在服务器端显示.

使用服务工作者的长解决方案失败了:

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

“构造'Request'失败:无法构造带有模式为'navigate'的Request和非空RequestInit的Request。”

【问题讨论】:

    标签: javascript webforms xmlhttprequest http-headers


    【解决方案1】:

    试试这个:-

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

    【讨论】:

    • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并最终将这些知识应用到他们自己的代码中。在解释代码时,您也可能会得到用户的积极反馈/赞成。
    【解决方案2】:

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

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

    另外,如果你使用一个常量、变量来存储headers的值和名称,浏览器会将变量的名称(小写)作为header的名称(不是它的值)。

    【讨论】:

      【解决方案3】:

      你需要实例化XMLHttpRequest to use it

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

      您不会直接使用Request...这是由modern fetch(..) API 在内部创建的。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多