2016-11-23 1 views
-2

다음과 같은 JS 함수가 html 페이지로드에서 호출됩니다. 페이지가로드 될 때 Firefox 콘솔 로그에 다음 오류가 표시됩니다.다른 휴식 서비스를 치고있는 순수 JavaScript로 AJAX 호출에서 CORS 헤더를 설정하는 방법은 무엇입니까?

파이어 폭스 콘솔 로그 :

"NetworkError: 403 Forbidden - http://localhost:8080/publicKey/lookup/TRUUS2" 
TRUUS2 
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/publicKey/lookup/TRUUS2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). 

publickey.js

function loadPublicKey() { 

    var xmlhttp = createCORSRequest('GET', 'http://localhost:8080/publicKey/lookup/TRUUS2'); 
    xmlhttp.send(); 

    xmlhttp.onreadystatechange = function() { 
     if (this.readyState === 4 && this.status === 200) { 
      alert(this.responseText); 
      document.getElementById("keyDiv").innerHTML = this.responseText; 
     } 
    }; 
} 


function createCORSRequest(method, url) { 
    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr) { 
     // Check if the XMLHttpRequest object has a "withCredentials" property. 
     // "withCredentials" only exists on XMLHTTPRequest2 objects. 
     xhr.open(method, url, true); 
    } else if (typeof XDomainRequest != "undefined") { 
     // Otherwise, check if XDomainRequest. 
     // XDomainRequest only exists in IE, and is IE's way of making CORS requests. 
     xhr = new XDomainRequest(); 
     xhr.open(method, url); 
    } else { 
     // Otherwise, CORS is not supported by the browser. 
     xhr = null; 
    } 
    xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); 
    return xhr; 
} 

나는 이미 CORS 문제지만 행운을 해결하기 위해 xhr.setRequestHeader("Access-Control-Allow-Origin", "*") 문을 추가했습니다. 나는 순수한 JS 구현을 찾고있다.

참고 : 나는 우체부를 통해 http://localhost:8080/publicKey/lookup/TRUUS2 URL을 성공적으로 방문하여 응답을받을 수 있습니다. 거기에는 문제가 없습니다.

내가 무엇이 실종되었는지 확실하지 않습니다. 안내해주십시오.

+1

CORS의 작동 원리를 오해하고 있습니다. 요청에 헤더를 넣지 마십시오. * 응답 *에 있어야합니다. 서버 측 코드를 수정해야합니다. –

+0

감사합니다. Rory, 당신 말이 맞았습니다. 이 게시물을 내 대답과 함께 업데이트했습니다. – user2325154

답변

0

Rory에서 제공 한 입력을 기반으로 JS에서 xhr.setRequestHeader("Access-Control-Allow-Origin", "*")을 제거하고 내 컨트롤러에 @CrossOrigin(origins = "http://localhost:8084") 스 니펫을 추가했는데 문제가 해결되었습니다.

@CrossOrigin(origins = "http://localhost:8084") 
@RestController 
public class PublicKeyLookupController { 
    //code removed for brevity 
} 
관련 문제