How can I add a custom HTTP header to ajax request with js or jQuery?

前端 未结 9 1130
独厮守ぢ
独厮守ぢ 2020-11-22 03:17

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

相关标签:
9条回答
  • 2020-11-22 03:56

    You should avoid the usage of $.ajaxSetup() as described in the docs. Use the following instead:

    $(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
        jqXHR.setRequestHeader('my-custom-header', 'my-value');
    });
    
    0 讨论(0)
  • 2020-11-22 03:56

    You can use js fetch

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

    0 讨论(0)
  • 2020-11-22 03:59

    Assuming JQuery ajax, you can add custom headers like -

    $.ajax({
      url: url,
      beforeSend: function(xhr) {
        xhr.setRequestHeader("custom_header", "value");
      },
      success: function(data) {
      }
    });
    
    0 讨论(0)
  • 2020-11-22 04:00

    Here's an example using 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++;
    }; 
    

    Hope that helps.

    If you create your object, you can use the setRequestHeader function to assign a name, and a value before you send the request.

    0 讨论(0)
  • 2020-11-22 04:03

    Or, if you want to send the custom header for every future request, then you could use the following:

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

    This way every future ajax request will contain the custom header, unless explicitly overridden by the options of the request. You can find more info on ajaxSetup here

    0 讨论(0)
  • 2020-11-22 04:04

    Assuming that you mean "When using ajax" and "An HTTP Request header", then use the headers property in the object you pass to ajax()

    headers(added 1.5)

    Default: {}

    A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

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

    0 讨论(0)
提交回复
热议问题