본문 바로가기

WebDev/Backend

Cross Domain AJAX

Cross Domain AJAX


AJAX. 잘 활용하면 RestfulAPI기반의 웹앱 만들기에 좋다.

그러나 웹사이트를 만들다 보면 용도에 맞게 도메인을 분리할 수 있다.

예를 들어, 웹은 www.mysite.com API는 api.mysite.com과 같이.


ajax 요청을 받는 도메인이 모두 www.mysite.com에서만 일어난다면 아무 문제가 없다.

그러나 도메인이 다르다면 온갖 문제가 발생하기 시작한다...


서버에서 할 일


서버에서는 아래와 같이 두가지 헤더를 반드시 Response Header에 포함시켜야 한다

  1. Access-Control-Allow-Credentials:true
  2. Access-Control-Allow-Origin:null

보안을 위해 Access-Control-Allow-Origin의 값은 개발용으로만 null을 지정하자.

실제 deploy 환경에서는 www.mysite.com와 같이 특정 도메인만을 지정하는 것이 좋다.



클라이언트에서 할 일


클라이언트에서 할 일은 모든 ajax 요청에 xhr설정을 지정하는 것이다.


적절한 로그인과, 로그아웃의 예는 다음과 같다

<script>
$.ajax('http://api.mysite.com/login', {
type: 'post',
data: $('form').serialize(),
success: function (data) {
$('#input').val(data);
},
xhrFields: {
withCredentials: true
}
});
$('#logout').click(function () {
$.ajax('http://api.mysite.com/logout', {
type: 'post',
data: $('form').serialize(),
success: function (data) {
$('#input').val(data);
},
xhrFields: {
withCredentials: true
}
})
});
</script>

withCredentials가 주요한 설정으로, 이 설정이 있어야 Request Header에 세션 쿠키 정보가 딸려간다.





'WebDev > Backend' 카테고리의 다른 글

DynamoDB Operator  (0) 2016.01.24
django deploy with sqlite3  (0) 2016.01.22
AWS boto accessKey, secretKey  (0) 2015.11.18
boto dynamodb2 사용하기  (0) 2015.11.18
Spring boot properties  (0) 2015.11.05