ajax의 옵션에 header를 포함시킬때, method에 어떤걸 정의하던 상관 없이 method값이 options로 변화 되는 경우가 있다.
Laravel의 경우 ajax시에 csrf_token을 사용하게 되면 header에 X-CSRF-TOKEN값을 포함 시켜야 하기 때문에, method에 post라고 명시해도 options로 가는 경우가 있다.
아래의 예를 보자
function test_ajax(){
$.ajax({
type: "post"
,url: "http://b1ix.net/test_ajax"
,dataType:'json'
,headers: {
'X-CSRF-TOKEN': '1pfAvflTTW19FHo6RYpKhMpIaZkiGpCJAU9Y3fUI'
}
,xhrFields: {
withCredentials: true
}
,success: function(data){
console.log(data)
}
,error: function(xhr, status, msg){
console.log(xhr, status, msg)
}
});
}
Request URL: http://b1ix.net/test_ajax
Request Method: OPTIONS
Status Code: 200 OK
...
위처럼 method에 post라고 되어 있는데 실제로 개발자 도구에서 Headers를 살펴보면, request Method에 OPTIONS라고 되어 있는것을 볼 수 있다.
이럴때는 아래처럼 data부분에 "_token"이라는 key값을 추가하고 csrf_token값을 넣어주면 된다.
function test_ajax(){
$.ajax({
type: "post"
,url: "http://b1ix.net/test_ajax"
,data: {
'_token': '1pfAvflTTW19FHo6RYpKhMpIaZkiGpCJAU9Y3fUI'
}
,dataType:'json'
,xhrFields: {
withCredentials: true
}
,success: function(data){
console.log(data)
}
,error: function(xhr, status, msg){
console.log(xhr, status, msg)
}
});
}
Request URL: http://b1ix.net/test_ajax
Request Method: POST
Status Code: 200 OK
...