2017-01-30 15 views
9

Próbuję dodać nagłówek do żądania w Ajaxie z JQuery.Jak dodać nagłówek do zapytania w Ajax Jquery?

Poniżej znajduje się kod: -

$.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); 
    } 
});

Obejrzałem ten z chromem i znalazł ciało nagłówek ten nie jest dodawana. Without Header Body

Następnie użyłem Requestly (Requestly jest chrom + wtyczki firefox, z którym możemy ręcznie dodać nagłówek do wniosku).

Po ręczne dodawanie nagłówka: -

After Manually Adding the header

W obu fotki zażądać nagłówka X-auth-znak jest obecny w "ACCESS-Control-request-headers" ale "X-auth token" nagłówek wraz z wartością nagłówka jest obecny na drugim zdjęciu, którego nie ma na pierwszym zdjęciu.

Moje pytanie brzmi: jak dodać nagłówki żądań w Ajaxie z JQuery?

Odpowiedz

16

Istnieje kilka rozwiązań, w zależności od tego, co chcesz zrobić

Jeśli chcesz dodać nagłówek niestandardowy (lub zestaw nagłówków) do indywidualnego wniosku potem po prostu dodać właściwość headers i to pomoże wysłać twoją prośbę z nagłówkami.

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

Jeśli chcesz dodać domyślny nagłówek (lub zestaw nagłówków) na każde żądanie następnie użyć $.ajaxSetup(): pomoże Ci dodać nagłówki.

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

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

dodać nagłówek (lub zestaw nagłówków) na każde żądanie następnie użyj haka beforeSend z $ .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

Powiązane problemy