0
return
CORS 요청의 응답 코드는 어떻게 작성합니까? 나는 onload 이벤트에서 그것을 얻을 수 있지만, 나는 그것을 꺼내서 return
을 만들어서 값 확인을 위해 잡을 수는없는 것처럼 보입니다. 여기 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
}
응답이 반환되기 전에 '상태'를 반환하는 것처럼 보입니다. 'onerror','onload' 등의 이벤트가 비동기 적으로 발생하고'status' 코드 만 사용 가능할 것이라는 점을 고려해야합니다. 콜백 또는 약속이 도움이 될 수 있습니다. – Ankit
'makeCorsRequest'를 어떻게 호출하는지 공유 할 수 있습니까? – Ankit
안녕하세요 @AnkitMishra. 저는 AngularJS를 사용하고 있습니다. 그래서 저는 공장에서 이것을 다음과 같이 호출하고 있습니다.'statusCode = $ payments.makeCorsRequest();' – ralphcarlo