[Ajax] Crossdomain Problem.
Crossdomain Problem.
Web에서 Ajax 처리를 하기 위해 발생하는 문제중 하나가 Crossdomain관련된 문제이다.
서로 다른 domain에 대한 쿠키를 공유해야 하는데, 이 문제는 보안상의 문제도 있지만
쿠키에대한 공유가 되어야 세션처리가 가능하기 때문에 이를 위해 몇가지 설정이 필요하다.
첫번째. xhrFields의 withCredentials 필드추가.
xhrFields의 withCredentials 값을 true로 설정한다.
$.ajax({ type: 'POST', url: url, dataType: 'json', crossDomain: true, xhrFields: { withCredentials: true }, data: data }).success(function(result) { })
추가 전
Request Header에 쿠키값이 존재하지 않는다.
추가 후
쿠키값을 전송한다.
두번째. Access-Control-Allow의 Credentials 필드추가.
res.setHeader('Access-Control-Allow-Origin','http://192.168.0.200'); res.setHeader('Access-Control-Allow-Credentials','true');
추가가 안될 경우 아래와 같은 오류가 발생한다.
XMLHttpRequest cannot load http://192.168.0.100/v1.0/api/certify. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://192.168.0.200' is therefore not allowed access.
XMLHttpRequest cannot load http://192.168.0.100/v1.0/api/certify. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.