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

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

This question is related to javascript jquery ajax http-headers httprequest

The answer is


There are several solutions depending on what you need...

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

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

If you want to add a default header (or set of headers) to every request then use $.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' } });

If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.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' } });

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.


Assuming JQuery ajax, you can add custom headers like -

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

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

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.


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


You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

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;

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/


You can use js fetch

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


"setRequestHeader" method of XMLHttpRequest object should be used

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to http-headers

Set cookies for cross origin requests Adding a HTTP header to the Angular HttpClient doesn't send the header, why? Passing headers with axios POST request What is HTTP "Host" header? CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Using Axios GET with Authorization Header in React-Native App Axios get access to response header fields Custom header to HttpClient request Send multipart/form-data files with angular using $http Best HTTP Authorization header type for JWT

Examples related to httprequest

Http post and get request in angular 6 Postman: How to make multiple requests at the same time Adding header to all request with Retrofit 2 Understanding Chrome network log "Stalled" state Why is this HTTP request not working on AWS Lambda? Simulate a specific CURL in PostMan HTTP Request in Swift with POST method What are all the possible values for HTTP "Content-Type" header? How to get host name with port from a http or https request Why I get 411 Length required error?