0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Node.jsで簡単なアプリを作ってみよう

0
Last updated at Posted at 2025-11-29

Node.jsで簡単なアプリを作ってみよう

(参考文献)『Node.js超入門第4版』掌田津耶乃著 秀和システム

  1. デスクトップにnode-appフォルダを作成する
  2. VSCodeを開き作成したnode-appフォルダに移動
  3. 新しいファイル「app.js」を作成し以下のコードを入力←とあるが、何回やっても実行エラー。ChatGPTに聞いて別のコードでやっと動いた
title
/*本に記載してあるコード↓↓↓ これだと動かなかった。なぜ?*/
const http = require('http');

var server = http.createServer(
 (request,response)=>{
   response.end('Hello Node.js');
 }
);
server.listen(3000);
title
/*ChatGPTに聞いたコード↓↓↓ これでやっと動いた・・・*/
// Node.js の HTTP モジュールを読み込む
const http = require('http');

// サーバーを作成
const server = http.createServer((request, response) => {
  response.statusCode = 200;
  response.setHeader('Content-Type', 'text/plain');
  response.end('Hello World\n');
});

// サーバーを起動
server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

プログラムを実行してみよう

VSCodeで新しいターミナルを表示する。
node app.js

と入力しEnter

ブラウザで表示確認

にアクセスすると「Hello World」と表示される

コードの説明

変数 = require(モジュール名);

requireというメソッドを実行
requireメソッドはNode.js特有のモジュールローディングシステム

サーバーオブジェクトの作成

変数 = http.createServer(関数);

httpオブジェクトにある「createServer」というメソッドを呼び出す

(request, response) => {処理}

function(request, response) {処理}

と同じ意味

requestとresponseという2つの引数を持った関数が用意されている。

=による関数は、アロー関数という

この2つは、クライアントからサーバーへの要求、サーバーからクライアントへの返信のそれぞれを管理するためのもの

response.end('Hello Node.js');

引数で渡されたresponseという変数の「end」というメソッドを呼び出している
サーバーからクライアントへの返信に関するオブジェクト
endは、クライアントへの返信を終了するメソッド

つまり、アクセスしてきたクライアントにテキストを返信して終了している

server.listen(3000);

createServerで作成したhttp.Serverオブジェクトを待受状態にする
listenメソッドで待受状態にしている

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?