2016-12-24 41 views
-2

GitHubのAPIへのAPI呼び出しをしようとしています。XMLHttpRequestはブラウザでは動作しますが、ノードでは動作しません

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "https://api.github.com/search/users?q=mohamed3on"); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { 
     console.log(xhr.response); 
    } 
} 
xhr.send(); 

このコードは、ブラウザで実行するとJSONファイルを実行して返します。

{ "TOTAL_COUNT":1、 "incomplete_results":偽、 "アイテム":[ { "ログイン": "Mohamed3on"、 "ID":12295159、 "avatar_url": "https://avatars.githubusercontent.com/u/12295159?v=3" 、 "gravatar_id": ""、 "URL": "​​"、 "html_url": "https://github.com/Mohamed3on"、 "followers_url": "https://api.github.com/users/Mohamed3on/followers"、 "following_url": "https://api.github.com/users/Mohamed3on/following {/ other_user}"、 "gists_url": "https://api.github.com/users/Mohamed3on/gists {/ gist_id}"、 "starred_url": "https://api.github.com/users/Mohamed3on/starred {/所有者} {/レポ}」、 "subscriptions_url": "https://api.github.com/users/Mohamed3on/subscriptions"、 "organizations_url": "https://api.github.com/users/Mohamed3on/orgs"、 "repos_url": "https://api.github.com/users/Mohamed3on/repos"、 "events_url": "https://api.github.com/users/Mohamed3on/events {/プライバシー}" 、 "received_events_url": "https://api.github.com/users/Mohamed3on/received_events"、 "タイプ": "ユーザー"、 "site_admin":偽、 "スコア":49.68772 }]}しかし

、私はローカルで実行( WebstormまたはNode)

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; 
var xhr = new XMLHttpRequest(); 
xhr.open("GET", "https://api.github.com/search/users?q=mohamed3on"); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { 
     console.log(xhr.response); 
    } 
} 
xhr.send(); 

コンソールに何も出力されません。

+0

同期要求をしないでください。これは廃止され、ひどい習慣で、 'onreadystatechange'コールバックを使用します。 – charlietfl

+0

@charlietflそれで、やりました。しかし、ノードではまだ出力が生成されません。 –

+0

なぜノードで 'XMLHttpRequest'を使うのですか? – charlietfl

答えて

2

あなたは、サーバーへのHTTP/HTTPSリクエストを作成するための要求モジュールを使用する必要があります。

var request = require('request-promise'); 

var aUrl = "https://api.github.com/search/users"; 

var reqOptions = { 
    method: 'GET', 
    uri: aUrl, 
    qs: { 
    q: 'rohankanojia' 
    }, 
    headers: { 
    'user-agent': 'node.js' 
    }, 
    json: true 
}; 

request(reqOptions) 
    .then(function(parsedBody) { 
    console.log("Got response : "+JSON.stringify(parsedBody)); 
    }) 
    .catch(function(err) { 
    console.log("request failed : "+err); 
    }); 

また、あなたがリクエストヘッダにユーザエージェントを渡していません。それは私のシステムで正常に動作します:

[email protected]~/Documents/src : $ node request.js 
Got response : {"total_count":1,"incomplete_results":false,"items":[{"login":"rohanKanojia","id":13834498,"avatar_url":"https://avatars.githubusercontent.com/u/13834498?v=3","gravatar_id":"","url":"https://api.github.com/users/rohanKanojia","html_url":"https://github.com/rohanKanojia","followers_url":"https://api.github.com/users/rohanKanojia/followers","following_url":"https://api.github.com/users/rohanKanojia/following{/other_user}","gists_url":"https://api.github.com/users/rohanKanojia/gists{/gist_id}","starred_url":"https://api.github.com/users/rohanKanojia/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/rohanKanojia/subscriptions","organizations_url":"https://api.github.com/users/rohanKanojia/orgs","repos_url":"https://api.github.com/users/rohanKanojia/repos","events_url":"https://api.github.com/users/rohanKanojia/events{/privacy}","received_events_url":"https://api.github.com/users/rohanKanojia/received_events","type":"User","site_admin":false,"score":29.729874}]} 

クライアント側で同じことを行うために:

<body> 
<script> 

function httpGet(theURL) { 
    var xmlHttp = new XMLHttpRequest(); 
    xmlHttp.open("GET", theURL); 
    xmlHttp.setRequestHeader("Content-Type", "application/json"); 
    xmlHttp.send(null); 


    xmlHttp.onreadystatechange = function() { 
    var response = null; 
    if(xmlHttp.readyState == XMLHttpRequest.DONE) { 
     response = xmlHttp.responseText; 
     document.getElementById("response").value = response; 
    } 
    }; 
} 

</script> 

<input id="clickMe" type="button" value="get Data" 
    onclick="httpGet('https://api.github.com/search/users?q=rohankanojia')" /> 

<br> 
Response : <input id="response" type="label"/> 
</body> 

私はそれが役に立てば幸い。

+2

OPはnode.jsのクライアントサイドコードをテストしようとしているようですしたがって、ブラウザで利用できないnode.js関数を使用するようにコードを書き直すことは、おそらくこの質問に関するものではありません。 – jfriend00

+0

はい@ jfriend00です。私のプロジェクトは主にGithub APIを扱っています。バックエンドを必要とせずにクライアント側(APIとのやりとり、結果の表示)で行うことができると思うので、すべてのコードをクライアント側。 –

+0

ちょっと、通常のHTTPリクエストを作成しますが、サーバがリクエストのタイプを識別できるようにxmlHttpRequestでなければなりません 特定のヘッダがある必要があります –

0

最初に、node.jsは、ブラウザで動作するように設計されたコードのための良いテスト環境ではなく、ECMAScript標準の一部ではないブラウザ機能を使用します。

XMLHttpRequestはブラウザ機能です。一般的なJavascriptやnode.jsの一部ではありません。したがって、XMLHttpRequestを使用するnode.jsでコードを実行しようとすると、そのオブジェクトが存在しないため動作しません。

node.jsにはHTTPリクエストを行うことができるhttp.get()がありますが、それはブラウザには存在しないため、node.jsで実行するようにコードを変更すると実行されませんブラウザに表示されます。

node.jsのオブジェクトを実装するnode.jsのライブラリはXMLHttpRequestですが、node.jsコードをネイティブに書く場合は、request()ライブラリなどのHTTPリクエストを作成する方がはるかに優れています。

ブラウザで実行するコードをテストし、ブラウザ固有の機能を使用する場合は、そのコードをブラウザ自体でテストするか、ブラウザをシミュレートするように設計された特定の製品を使用するだけですテスト環境。それ以外の場合は、ブラウザー固有のものをnode.jsで実行するようにアダプテーションを行ってから、同じコードをテストしないことがあります。

+0

私はちょうど最初からNodeを使うべきでしょうか? –

+1

@MohamedOun - それはあなたのアプリケーションに完全に依存します。ブラウザが必要ない場合は、ノードを使用します。 – jfriend00

関連する問題