Development

Cross 도메인 설정

chbae 2023. 4. 19. 02:00
728x90
반응형

필자는 CROS 도메인 문제를 겪어 해결 방법에 대해 간단히 적어본다.

 

CROS 도메인 문제는 아래 그림에서 보는 것과 같이, http://domainA에서 http://domainB로 resource로 요청할 경우 domain이 달라서 나타나는 문제이다.

CROS에 대한 설명은 http://adrenal.tistory.com/16를 참고해 보기 바란다. 다음은 필자가 겪었던 문제이다.

문제점

xmlhttprequest로 파일 서버에 있는 목록을 요청해서 파싱처리하려고 했다. 파일 목록은 html로 온다. 파일 서버와 소스가 있는 http 서버가 같은 도메인일 때는 아무 문제 없이 돌아갔지만, 소스가 있는 http 서버를 다른 곳으로 이동하니 아래와 같은 문제가 발생했다. 참고) 파일 서버도 http에서 다운 받을 수 있도록 웹서버를 제공했다.

발생한 에러

XMLHttpRequest cannot load [파일 서버. ex) http://fileserver.com/directory]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '[javascript 소스]' is therefore not allowed access.

해결 Step #1

파일 서버의 apache에 000-default.conf 파일의 <VirtualHost *:80> 밑에 아래와 같이 추가하고 apache 서버를 재시작($ sudo service apache2 restart) 했다.

<IfModule mod_headers.c>  
    Header set Access-Control-Allow-Origin "*"  
</IfModule>

 

일반적으로 위와 같이 하면 해결된다. 하지만 이후에도 필자는 같은 문제가 발생하여 curl로 테스트 해보니 아래와 같이 Header에 Access-Control-Allow-Origin도 포함안되고 http response 코드가 정상적으로 200이 오지 않았다.

 $ curl -i http://fileserver.com/directory
 HTTP/1.1 301 Moved Permanently  
 Date: Sat, 22 Aug 2015 00:54:11 GMT  
 Server: Apache/2.4.7 (Ubuntu)  
 Location: http://fileserver.com/directory/  
 Content-Length: 332  
 Content-Type: text/html; charset=iso-8859-1  
 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">  
 <html><head>  
 <title>301 Moved Permanently</title>  
 </head><body>  
 <h1>Moved Permanently</h1>  
 <p>The document has moved <a href="http://fileserver.com/directory/">here</a>.</p>  
 <hr>  
 <address>Apache/2.4.7 (Ubuntu) Server at fileswp.lge.com Port 80</address>  
 </body></html>

해결 Step #2

자세히 읽어보니 directory 요청시 주소 끝에 /를 붙여주면 되는 것 같다. 그래서 코드에서 xmlHttp.open('GET', url, true); 요청시 url의 제일 끝에 /를 붙여 주니 아래와 같이 헤더에 Access-Control-Allow-Origin이 정상적으로 붙여 왔다.

 changhyeok.bae@scmbuild1~ $ curl -i http://fileserver.com/directory
 HTTP/1.1 200 OK  
 Date: Sat, 22 Aug 2015 00:42:45 GMT  
 Server: Apache/2.4.7 (Ubuntu)  
 Vary: Accept-Encoding  
 Access-Control-Allow-Origin: *  
 Content-Length: 1588  
 Content-Type: text/html;charset=UTF-8  
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">  
 <html>  
  <head> .........
728x90