Nodejs-first-application
提供:Dev Guides
Node.js-最初のアプリケーション
実際の「Hello、World!」を作成する前にNode.jsを使用するアプリケーション、Node.jsアプリケーションのコンポーネントを見てみましょう。 Node.jsアプリケーションは、次の3つの重要なコンポーネントで構成されています-
- 必要なモジュールのインポート-Node.jsモジュールをロードするために require ディレクティブを使用します。
- サーバーの作成-Apache HTTPサーバーと同様に、クライアントのリクエストをリッスンするサーバー。
- 要求を読み取り、応答を返す-前の手順で作成されたサーバーは、ブラウザまたはコンソールである可能性のあるクライアントによって行われたHTTP要求を読み取り、応答を返します。
Node.jsアプリケーションの作成
ステップ1-必要なモジュールのインポート
*require* ディレクティブを使用してhttpモジュールをロードし、返されたHTTPインスタンスを次のようにhttp変数に保存します-
var http = require("http");
ステップ2-サーバーの作成
作成されたhttpインスタンスを使用して* http.createServer()メソッドを呼び出してサーバーインスタンスを作成し、サーバーインスタンスに関連付けられた *listen メソッドを使用してポート8081でバインドします。 パラメータのリクエストとレスポンスを含む関数を渡します。 サンプル実装を記述して、常に「Hello World」を返します。
http.createServer(function (request, response) {
//Send the HTTP header
//HTTP Status: 200 : OK
//Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
//Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
//Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
上記のコードは、リッスンする、つまり、ローカルマシンの8081ポートでリクエストを待機するHTTPサーバーを作成するのに十分です。
ステップ3-要求と応答のテスト
ステップ1と2を main.js というファイルにまとめて、以下に示すようにHTTPサーバーを起動しましょう-
var http = require("http");
http.createServer(function (request, response) {
//Send the HTTP header
//HTTP Status: 200 : OK
//Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
//Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
//Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
今すぐmain.jsを実行して、次のようにサーバーを起動します-
$ node main.js
出力を確認します。 サーバーが起動しました。
Server running at http://127.0.0.1:8081/
Node.jsサーバーにリクエストを行う
任意のブラウザーでhttp://127.0.0.1:8081/を開き、次の結果を確認します。
おめでとうございます。ポート8081ですべてのHTTP要求に応答している最初のHTTPサーバーが稼働しています。