프로그래밍/Delphi
Same origin policy 때문에 다른 포트로 jQuery에서 get이나 post를 할 수 없을 때
ryujt
2012. 5. 22. 16:24
오늘 한 동안 이것 때문에 고생하다가, 검색해보니, Same origin policy 때문에 원래 안되는 걸 엉뚱한 자바스크립트만 이리 저리 바꾸고 있었습니다 ㅠ.ㅠ
여하튼 해결 방법은 Response Header에 "Access-Control-Allow-Origin: *"를 추가하는 것 입니다. 아래 소스는 델파이로 만든 웹 서버에서 이를 처리하는 예제 입니다.
type TfmMain = class(TForm) IdHTTPServer: TIdHTTPServer; moMsg: TMemo; procedure IdHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure IdHTTPServerException(AContext: TIdContext; AException: Exception); private public end; var fmMain: TfmMain; implementation {$R *.dfm} procedure TfmMain.IdHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); begin AResponseInfo.CustomHeaders.Values['Access-Control-Allow-Origin'] := '*'; AResponseInfo.ContentText := 'Hi'; end;
아래 소스는 jQuery를 이용해서 델파이로 만든 웹 서버에서 데이터를 쿼리하는 과정입니다.
<script type="text/javascript"> $.get('http://127.0.0.1:1234/Hello?', function(data) { alert('Result: ' + data); } ) .error(function() { alert("error"); }); </script>
[그림 1] 실행 결과