2016-07-14 2 views
0

return CORS 요청의 응답 코드는 어떻게 작성합니까? 나는 onload 이벤트에서 그것을 얻을 수 있지만, 나는 그것을 꺼내서 return을 만들어서 값 확인을 위해 잡을 수는없는 것처럼 보입니다. 여기 CORS 요청에 대한 상태 코드 받기

는 내 코드는 http://www.html5rocks.com/en/tutorials/cors/을 기반으로합니다 : 우리는 다른 함수에 매개 변수로 자바 스크립트 함수를 통과하고, 내부에서 비동기를 호출 할 수

createCORSRequest: function(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; 

    } 
    return xhr; 
    }, 

    makeCorsRequest: function() { 
    // All HTML5 Rocks properties support CORS. 
    var me = this; 
    var url = 'http://google.com'; 
    var sCode = ''; 

    var xhr = me.createCORSRequest('GET', url); 
    console.log('xhr', xhr); 
    if (!xhr) { 
     alert('CORS not supported'); 
     return; 
    } 

    // Response handlers. 
    xhr.onload = function() { 
     var text = xhr.responseText; 
     var sCode = xhr.status; 
     // var title = getTitle(text); 
     // alert('Response from CORS request to ' + url + ': ' + xhr.status); 
    }; 

    xhr.onreadystatechange = function() { 
     console.log(this.status); 
     sCode = this.status; 
    } 

    xhr.onerror = function() { 
     alert('Woops, there was an error making the request.'); 
    }; 

    xhr.send(); 
    return sCode; // this returns an empty string or the initial value set to it and not from `onload` event 
    } 
+0

응답이 반환되기 전에 '상태'를 반환하는 것처럼 보입니다. 'onerror','onload' 등의 이벤트가 비동기 적으로 발생하고'status' 코드 만 사용 가능할 것이라는 점을 고려해야합니다. 콜백 또는 약속이 도움이 될 수 있습니다. – Ankit

+0

'makeCorsRequest'를 어떻게 호출하는지 공유 할 수 있습니까? – Ankit

+0

안녕하세요 @AnkitMishra. 저는 AngularJS를 사용하고 있습니다. 그래서 저는 공장에서 이것을 다음과 같이 호출하고 있습니다.'statusCode = $ payments.makeCorsRequest();' – ralphcarlo

답변

3

한 가지 방법은, JS에서 콜백의 사용이 될 수 있습니다.

비동기 적으로 응답하도록 코드를 약간 수정했으며 관련 주석을 추가했습니다. 아래 callback의 사용을 관찰하십시오.

//make few changes to make it asynchronous. 
makeCorsRequest: function(callback) { 
    // All HTML5 Rocks properties support CORS. 
    var me = this; 
    var url = 'http://google.com'; 
    var sCode = ''; 

    var xhr = me.createCORSRequest('GET', url); 
    console.log('xhr', xhr); 
    if (!xhr) { 
     callback('CORS not supported'); 
     return; 
    } 

    // Response handlers. 
    xhr.onload = function() { 
     var text = xhr.responseText; 
     var sCode = xhr.status; 
     // var title = getTitle(text); 
     // alert('Response from CORS request to ' + url + ': ' + xhr.status); 
     callback(null, text); 
    }; 

    xhr.onreadystatechange = function() { 
     console.log(this.status); 
     callback(this.status); 
    } 

    xhr.onerror = function() { 
     callback('Woops, there was an error making the request.'); 
    }; 

    xhr.send(); 
    } 

//this function would be the callback, it would be called 'Asynchronously' form XHR events with err or real data. First parameter generally indicates error. 
function handleCorsResponse(err, data) { 
    //check if error occurred 
    if (err) { 
     //error handling here 
    } 

    //if no error occurred, proceed. 
    console.log(data); 
} 

//let's call `makeCorsRequest` with `handleCorsResponse` as a parameter. 
$payments.makeCorsRequest(handleCorsResponse); 

: 더 나은 권장 방법은 Promise을 사용하는 것입니다.

관련 문제