2017-01-30 1 views
9

JQuery로 Ajax에서 요청할 헤더를 추가하려고합니다. 다음은 Jquery Ajax에서 요청에 헤더를 추가하는 방법은 무엇입니까?

코드입니다 : -
$.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); 
    } 
});

나는 크롬이 검사 및 해당 헤더의 몸이 추가되지 않는 발견했다.

Without Header Body는 그럼 난 (Requestly 우리가 수동으로 요청에 헤더를 추가 할 수있는 크롬 + 파이어 폭스 플러그인은 ) Requestly을 사용했다.

수동 헤더를 추가 한 후 - 찍어 모두

After Manually Adding the header

헤더 X-인증 토큰은 "액세스 제어 요청 헤더"그러나 "X-AUTH 토큰"으로 존재 요청할 헤더 값과 함께 머리글은 첫 번째 그림에없는 두 번째 그림에 있습니다.

제 질문은 JQuery로 Ajax에서 요청 헤더를 추가하는 방법입니다.

답변

16

가 당신이 다음 단지 headers 속성을 추가 개별 요청에 대한 사용자 정의 헤더 (또는 헤더 세트)를 추가하려면

을 수행하려는 작업에 따라 솔루션의 부부는이 당신을 도울 것입니다 헤더로 요청을 보냅니다. 모든 요청에 ​​기본 헤더 (또는 헤더 세트)를 추가하려면

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

다음이 헤더를 추가하는 데 도움이됩니다 $.ajaxSetup(): 사용합니다.

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

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

헤더 추가 (또는 헤더 집합) 모든 요청 후 $ .ajaxSetup()와 beforeSend 후크 사용하려면,

//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

관련 문제