2017-11-08 9 views
-1

XHTMLリクエストをREST APIに送信しようとしましたが、回答が得られません。私はそれをステートメすると、XHRステータスが未定義

<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> 

xhr.statusは未定義のままで、それがif (xhr.status === 200)に入ることはありません:

は、ここに私のコードです。どうしてか分かりません。誰か助けてくれますか?

編集:

私はJSONを固定されているが、私はまだエラーを持っている:

Google Chrome console showing an error.

誤差はおよそ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.

だから、私はthis topicを読みますそれは私がAccess-Control-Allow-Origin : *をHTTPヘッダーに追加する必要があると言いますn mocky.io。私はそれを行うが、それは何も変わりません:ここで

enter image description here

を新しいmocky.io URLです:私のミスがどこにある

http://www.mocky.io/v2/5a083d8e2f0000c61ee61140 

誰もが見ていますか?

+0

まあ、readyStateとは何ですか?あなたはそれが4になるまでステータスを取得しません。 – epascarello

+0

私のクロームコンソールでjsコードを実行し、 'if(xhr.status === 200)' – JohanP

+1

を入力します。https://jsfiddle.net/79Lcvv1k/いくつかの出力が追加されたあなたのコードです - だから...問題はサーバ側のコードであったのですが、これは固定されているからです –

答えて

0

私たちがローカルでHTMLファイルにアクセスすると、Access-Control-Allow-Origin : *は無視されるようです(file:///C:/.../index.htmlから)。

ローカルサーバー(たとえば、this Chrome extension)をマウントし、HTTP(http://127.0.0.1:8887/index.html)でHTMLファイルにアクセスする必要があります。

またはthis other Chrome extensionを使用すると、自動的にAccess-Control-Allow-Origin : *がHTTP応答のヘッダーに追加されます。

関連する問題