Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add header to request in Jquery Ajax?

I'm trying to add header to request in Ajax with JQuery.

Below is the code :-

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "http://localhost:8080/core-service/services/v1.0/patients/registerPatients",
    data: JSON.stringify(patientDTO),
    //crossDomain : true,
    dataType: 'json',
    headers: {"X-AUTH-TOKEN" : tokken},
    success: function(patientDTO) {
        console.log("SUCCESS: ", patientDTO);
        /* location.href = "fieldagentHRA.html";*/
        if (typeof(Storage) !== "undefined") {
            localStorage.setItem("patUrn", patientDTO.data);
            location.href="fieldagentHRA.html";
        }
    },
    error: function(e) {
    console.log("ERROR: ", e);
    display(e);
    },
    done: function(e) {
    enableRegisterButton(true);
    }
});

I inspected this with chrome and found that header's body is not being added.Without Header Body

Then I used Requestly (Requestly is chrome+firefox plugin with which we can manually add a header to the request).

After manually adding header :-

After Manually Adding the header

In both the pics request header x-auth-token is present in "ACCESS-CONTROL-REQUEST-HEADERS" but "X-AUTH-TOKEN" header along with header value is present in second pic which is not there in the first pic.

So my question is how to add request headers in Ajax with JQuery ?

like image 481
Safdar Akrami Avatar asked Jan 30 '17 05:01

Safdar Akrami


1 Answers

There are couple of solutions depending on what you want to do

If want to add a custom header (or set of headers) to an individual request then just add the headers property and this will help you to send your request with headers.

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

If want to add a default header (or set of headers) to every request then use $.ajaxSetup(): this will help you to add headers.

//Setup headers here and than call ajax
$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your ajax
$.ajax({ url: 'foo/bar' });

add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

//Hook your headers here and set it with before send function.
$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your ajax
$.ajax({ url: 'foo/bar' });

Reference Link : AjaxSetup

Reference Link : AjaxHeaders

like image 183
Soni Vimalkumar Avatar answered Nov 04 '22 21:11

Soni Vimalkumar