본문으로 건너뛰기

헤더와 토큰

Ajax에서 헤더에 토큰을 넣어서 보내보자

Ajax에서 헤더 부분에 Content-type혹은 토큰 정보를 넣어서 보내야 할 때가 있다.
이럴 때는 beforeSend를 사용한다

function getInform() {
var token = localStorage.getItem("token");
$.ajax({
type: "POST",
url: "/getEmployeeInformation",
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Authorization","JWT " + token);
},
success: function (res) {
console.log(res);
}
});
}

다른 예제도 보자

function to_ajax(){

$.ajax({
type : 'get',
url : '/test.jsp,
dataType : 'xml',
beforeSend : function(xhr){
xhr.setRequestHeader("ApiKey", "asdfasxdfasdfasdf");
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
},
error: function(xhr, status, error){
alert(error);
}
success : function(xml){
alert(xml)
},
});
}

이것도 다른예제.

jwt, Content-type등 헤더부분을 추가할 때 beforeSend에 넣어주면 된다고 동일하게 얘기하고 있다.
이 예제는 header부분에 Content-type과 JWT토큰을 추가하는 예제이다.

function test() {
var token = localStorage.getItem("token");
$.ajax({
type: "GET",
url: "/api/test",
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-type","application/json");//header추가
xhr.setRequestHeader("Authorization","JWT " + token);//header추가
},
success: function (res) {
console.log(res);
}
});
}

다른 예제도 몇가지 보자

meta 태그 안에있는 content를 가져와서
Ajax beforeSend(데이터를 전송하기전) 에 HTTP Header를 SET 해준다고 한다.
스프링에서 Spring Security 를 쓰게 되면 꼭 해줘야 한다.
Ajax호출시 토큰값을 헤더에 잘 넘겨주기만 하면 된다는것이 포인트
서버단에서 딱히 할것은 없다.

$(function() {
$("#ajaxCall").click(function(){
ajaxCall();
});
});

function ajaxCall(){
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var name = $("#userName").val();

var jsonData = {
"name" : name
}

$.ajax({
type: 'POST',
contentType: "application/json",
url:'/csrf/ajax',
data: JSON.stringify(jsonData), // String -> json 형태로 변환
beforeSend : function(xhr)
{ /*데이터를 전송하기 전에 헤더에 csrf값을 설정한다*/
xhr.setRequestHeader(header, token);
},
dataType: 'json', // success 시 받아올 데이터 형
async: true, //동기, 비동기 여부
cache :false, // 캐시 여부
success: function(data){
console.log(data.name);
},
error:function(xhr,status,error){
console.log('error:'+error);
}
});
}