【问题标题】:How can I add a custom HTTP header to ajax request with js or jQuery?如何使用 js 或 jQuery 向 ajax 请求添加自定义 HTTP 标头?
【发布时间】:2011-12-02 23:07:06
【问题描述】:

有人知道如何使用 JavaScript 或 jQuery 添加或创建自定义 HTTP 标头吗?

【问题讨论】:

    标签: javascript jquery ajax http-headers httprequest


    【解决方案1】:

    根据您的需要,有几种解决方案...

    如果您想为单个请求添加自定义标头(或一组标头),则只需添加 headers 属性:

    // Request with custom header
    $.ajax({
        url: 'foo/bar',
        headers: { 'x-my-custom-header': 'some value' }
    });
    

    如果您想为每个请求添加一个默认标头(或一组标头),请使用$.ajaxSetup()

    $.ajaxSetup({
        headers: { 'x-my-custom-header': 'some value' }
    });
    
    // Sends your custom header
    $.ajax({ url: 'foo/bar' });
    
    // Overwrites the default header with a new header
    $.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
    

    如果您想为每个请求添加一个标头(或一组标头),请使用 beforeSend 钩子和 $.ajaxSetup()

    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('x-my-custom-header', 'some value');
        }
    });
    
    // Sends your custom header
    $.ajax({ url: 'foo/bar' });
    
    // Sends both custom headers
    $.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
    

    编辑(更多信息):需要注意的一点是,使用ajaxSetup,您只能定义一组默认标头,并且您只能定义一个beforeSend。如果多次调用ajaxSetup,只会发送最后一组headers,并且只会执行最后一个before-send回调。

    【讨论】:

    • 如果我在执行$.ajax 时定义一个新的beforeSend 会发生什么?
    • 你只能定义一个beforeSend回调。如果您调用$.ajaxSetup({ beforeSend: func... }) 两次,那么第二个回调将是唯一触发的回调。
    • 更新了我的答案以添加有关ajaxSetup 的更多详细信息。
    • 看起来它不适用于 CORS 请求(每个浏览器)。有解决办法吗?
    • @Si8,这对我来说似乎是一个跨域问题。您不能从一个域向另一个域发出请求。尝试查看 CORS,看看是否有帮助。
    【解决方案2】:

    或者,如果您想为以后的每个请求发送自定义标头,那么您可以使用以下内容:

    $.ajaxSetup({
        headers: { "CustomHeader": "myValue" }
    });
    

    这样,每个未来的 ajax 请求都将包含自定义标头,除非被请求的选项明确覆盖。你可以在ajaxSetuphere找到更多信息

    【讨论】:

    • 我真的想完成这个,这似乎并没有真正起作用。
    • 那么您应该确保在实际的 ajax 调用之前调用 ajaxSetup。我不知道这不起作用的任何其他原因:)
    【解决方案3】:

    您也可以在不使用 jQuery 的情况下执行此操作。覆盖 XMLHttpRequest 的 send 方法并在此处添加标头:

    XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
    var newSend = function(vData) {
        this.setRequestHeader('x-my-custom-header', 'some value');
        this.realSend(vData);
    };
    XMLHttpRequest.prototype.send = newSend;
    

    【讨论】:

      【解决方案4】:

      假设 JQuery ajax,您可以添加自定义标题 -

      $.ajax({
        url: url,
        beforeSend: function(xhr) {
          xhr.setRequestHeader("custom_header", "value");
        },
        success: function(data) {
        }
      });
      

      【讨论】:

        【解决方案5】:

        这是一个使用 XHR2 的示例:

        function xhrToSend(){
            // Attempt to creat the XHR2 object
            var xhr;
            try{
                xhr = new XMLHttpRequest();
            }catch (e){
                try{
                    xhr = new XDomainRequest();
                } catch (e){
                    try{
                        xhr = new ActiveXObject('Msxml2.XMLHTTP');
                    }catch (e){
                        try{
                            xhr = new ActiveXObject('Microsoft.XMLHTTP');
                        }catch (e){
                            statusField('\nYour browser is not' + 
                                ' compatible with XHR2');                           
                        }
                    }
                }
            }
            xhr.open('POST', 'startStopResume.aspx', true);
            xhr.setRequestHeader("chunk", numberOfBLObsSent + 1);
            xhr.onreadystatechange = function (e) {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    receivedChunks++;
                }
            };
            xhr.send(chunk);
            numberOfBLObsSent++;
        }; 
        

        希望对您有所帮助。

        如果您创建对象,则可以在发送请求之前使用 setRequestHeader 函数分配名称和值。

        【讨论】:

        • 虽然这在 2011 年可能是正确的,但通常最好不要重新发明轮子,而是使用 Zepto 或 jQuery 等 AJAX 库。
        • 除非您尝试将标头添加到现有的 XHR2 调用并且不想开始重写它以使用 jQuery 只是为此...此时,@gryzzly 是唯一可行的回答。
        • @AliGajani 问题是某些应用程序或库(如 THREE.js)不使用 $.ajax* 函数 b/c 他们不依赖 jQuery 而是使用 XHR 所以这是在这些情况下唯一有效的选项。
        • @AliGajani 此外,这不仅仅是网络加载时间,还有库的解析时间。另外,如果你不小心添加了哪些依赖项,你会很快得到一个依赖项太多的项目
        【解决方案6】:

        您应该避免使用$.ajaxSetup(),如docs 中所述。请改用以下内容:

        $(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
            jqXHR.setRequestHeader('my-custom-header', 'my-value');
        });
        

        【讨论】:

          【解决方案7】:

          假设您的意思是“使用 ajax 时”和“一个 HTTP Request 标头”,则在传递给 ajax() 的对象中使用 headers 属性

          标题(添加 1.5)

          默认:{}

          与请求一起发送的附加标头键/值对的映射。此设置在调用 beforeSend 函数之前设置;因此,headers 设置中的任何值都可以在 beforeSend 函数中被覆盖。

          ——http://api.jquery.com/jQuery.ajax/

          【讨论】:

            【解决方案8】:

            应该使用XMLHttpRequest对象的“setRequestHeader”方法

            http://help.dottoro.com/ljhcrlbv.php

            【讨论】:

              【解决方案9】:

              可以使用jsfetch

              async function send(url,data) {
                let r= await fetch(url, {
                      method: "POST", 
                      headers: {
                        "My-header": "abc"  
                      },
                      body: JSON.stringify(data), 
                })
                return await r.json()
              }
              
              // Example usage
              
              let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=my-header';
              
              async function run() 
              {
               let jsonObj = await send(url,{ some: 'testdata' });
               console.log(jsonObj[0].request.httpMethod + ' was send - open chrome console > network to see it');
              }
              
              run();

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2023-03-12
                • 2016-03-27
                • 2017-06-15
                • 1970-01-01
                • 2012-11-15
                • 1970-01-01
                • 2017-11-06
                相关资源
                最近更新 更多