Nodejs-web-module

提供:Dev Guides
移動先:案内検索

Node.js-Webモジュール

Webサーバーとは何ですか?

Webサーバーは、Webブラウザなど、HTTPクライアントから送信されたHTTP要求を処理し、クライアントへの応答としてWebページを返すソフトウェアアプリケーションです。 Webサーバーは通常、画像、スタイルシート、およびスクリプトとともにHTMLドキュメントを配信します。

ほとんどのWebサーバーは、スクリプト言語を使用するか、データベースからデータを取得して複雑なロジックを実行し、Webサーバーを介してHTTPクライアントに結果を送信するアプリケーションサーバーにタスクをリダイレクトするサーバー側スクリプトをサポートします。

Apache Webサーバーは、最も一般的に使用されるWebサーバーの1つです。 これはオープンソースプロジェクトです。

Webアプリケーションアーキテクチャ

Webアプリケーションは通常4つの層に分割されます-

Webアーキテクチャ

  • クライアント-この層は、Webサーバー、HTTPリクエストを行うことができるWebブラウザー、モバイルブラウザー、またはアプリケーションで構成されます。
  • サーバー-このレイヤーには、クライアントによって行われた要求をインターセプトし、それらに応答を渡すことができるWebサーバーがあります。
  • ビジネス-このレイヤーには、Webサーバーが必要な処理を行うために使用するアプリケーションサーバーが含まれます。 この層は、データベースまたはいくつかの外部プログラムを介してデータ層と対話します。
  • データ-このレイヤーには、データベースまたはその他のデータソースが含まれます。

Nodeを使用したWebサーバーの作成

Node.jsは、サーバーのHTTPクライアントを作成するために使用できる http モジュールを提供します。 以下は、8081ポートでリッスンするHTTPサーバーの最低限の構造です。

server.jsという名前のjsファイルを作成します-

  • ファイル:server.js *
var http = require('http');
var fs = require('fs');
var url = require('url');

//Create a server
http.createServer( function (request, response) {
  //Parse the request containing file name
   var pathname = url.parse(request.url).pathname;

  //Print the name of the file for which request is made.
   console.log("Request for " + pathname + " received.");

  //Read the requested file content from file system
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);

        //HTTP Status: 404 : NOT FOUND
        //Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      } else {
        //Page found
        //HTTP Status: 200 : OK
        //Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});

        //Write the content of the file to response body
         response.write(data.toString());
      }

     //Send the response body
      response.end();
   });
}).listen(8081);

//Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

次に、server.jsを作成したのと同じディレクトリに、indexという名前の次のhtmlファイルを作成します。

ファイル:インデックス

<html>
   <head>
      <title>Sample Page</title>
   </head>

   <body>
      Hello World!
   </body>
</html>

今、私たちは結果を見るためにserver.jsを実行しましょう-

$ node server.js

出力を確認します。

Server running at http://127.0.0.1:8081/

Node.jsサーバーにリクエストを行う

任意のブラウザーでhttp://127.0.0.1:8081/indexを開いて、次の結果を確認します。

最初のサーバーアプリケーション

サーバー側の出力を確認します。

Server running at http://127.0.0.1:8081/
Request for/index received.

Nodeを使用してWebクライアントを作成する

Webクライアントは、 http モジュールを使用して作成できます。 次の例を確認してみましょう。

client.jsという名前のjsファイルを作成します-

  • ファイル:client.js *
var http = require('http');

//Options to be used by request
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index'
};

//Callback function is used to deal with response
var callback = function(response) {
  //Continuously update stream with data
   var body = '';
   response.on('data', function(data) {
      body += data;
   });

   response.on('end', function() {
     //Data received completely.
      console.log(body);
   });
}
//Make a request to the server
var req = http.request(options, callback);
req.end();

今、結果を見るためにserver.js以外の別のコマンドターミナルからclient.jsを実行します-

$ node client.js

出力を確認します。

<html>
   <head>
      <title>Sample Page</title>
   </head>

   <body>
      Hello World!
   </body>
</html>

サーバー側の出力を確認します。

Server running at http://127.0.0.1:8081/
Request for/index received.