Ich versuche, eine XHR-Anforderung an eine REST-API zu senden, aber ich kann keine Antwort erhalten.XHR-Status nicht definiert
Hier ist mein Code:
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.mocky.io/v2/5a083d8e2f0000c61ee61140", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function() {
console.log("xhr.readyState: " + xhr.readyState);
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log("xhr.status: " + xhr.status);
if (xhr.status === 200) {
console.log("xhr.responseText: " + xhr.responseText);
var response = JSON.parse(xhr.responseText);
}
}
}
xhr.send();
console.log("xhr.readyState: " + xhr.readyState);
console.log("xhr.status: " + xhr.status);
</script>
Als ich es execut, xhr.status
bleibt undefiniert und es nie in der if (xhr.status === 200)
eingeben. Ich weiß nicht warum. Kann mir jemand helfen?
Edit:
ich die JSON fest, aber ich habe immer noch einen Fehler:
Der Fehler ist etwa Access-Control-Allow-Origin
:
Failed to load http://www.mocky.io/v2/5a083d8e2f0000c61ee61140 : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
So las ich this topic das sagt, dass ich Access-Control-Allow-Origin : *
im HTTP-Header o hinzufügen muss n mocky.io. Ich tue es, aber es ändert sich nichts:
Hier ist die neue mocky.io URL:
http://www.mocky.io/v2/5a083d8e2f0000c61ee61140
Hat jemand sehen, wo mein Fehler ist?
Nun, was ist der ReadyState? Du bekommst keinen Status, bis es 4 – epascarello
ist Ich habe diesen js-Code in meiner Chrome-Konsole ausgeführt und es gibt das 'if (xhr.status === 200)' – JohanP
siehe https://jsfiddle.net/79Lcvv1k/ - was ist dein Code mit etwas Ausgabe hinzugefügt - also ... Problem war mit dem serverseitigen Code, den du seit –