2016-07-14 3 views
0

Wie erhalten Sie return einen Antwortcode von einer CORS-Anfrage? Ich bin in der Lage, es von einem Onload-Ereignis zu bekommen, aber ich kann nicht scheinen, es herauszunehmen und return zu bilden, damit ich es für Wertüberprüfung fangen kann.Statuscode auf CORS-Anforderung abrufen

Hier ist mein Code basiert auf 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

Es sieht so aus, als würden Sie den 'Status' zurückgeben, bevor die Antwort zurückgegeben wird. Sie müssen möglicherweise berücksichtigen, dass die Ereignisse "onerror", "onload" usw. asynchron ausgelöst werden und nur dann steht Ihnen der Statuscode zur Verfügung. Rückrufe oder Versprechen könnten hilfreich sein. – Ankit

+0

Können Sie mitteilen, wie Sie zu makeCorsRequest aufrufen? – Ankit

+0

Hallo @AnkitMishra. Ich benutze AngularJS, also rufe ich es von meiner Fabrik so: 'statusCode = $ payments.makeCorsRequest();' – ralphcarlo

Antwort

3

Ein Ansatz ist die Verwendung von Callback in JS sein könnte, wie wir Funktionen in JavaScript als Parameter für andere Funktionen, und rufen sie asynchron von innen passieren kann.

Ich habe Ihren Code ein wenig geändert, damit er asynchron reagiert, und relevante Kommentare hinzugefügt. Beachten Sie die Verwendung von callback unten.

//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); 

Hinweis: Ein besserer und empfohlene Weg ein Promise verwenden würde.