17

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 ?

Sachin Jain
21.9k34 gold badges113 silver badges177 bronze badges
asked Jan 30, 2017 at 5:44

1 Answer 1

44

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

answered Feb 9, 2017 at 10:09
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.