サーバー起動方法について

This commit is contained in:
ry.yamafuji 2025-03-21 00:03:36 +09:00
parent 4ff8259c17
commit ecf620d6ac

View File

@ -1,6 +1,9 @@
## NodeでHttpサーバーを起動する方法 # [Node.js]NodeでHttpサーバーを起動及び構築する方法
### `http-server`を使う ## `http-server`を使う場合
http-serverはNode.js のシンプルな静的ファイルサーバーです。
インストールすれば簡単にローカルでファイルをホスティングできます。
```sh ```sh
# http-server をグローバルインストール(初回のみ) # http-server をグローバルインストール(初回のみ)
@ -12,4 +15,72 @@ cd src/front
# サーバー起動(デフォルトは http://localhost:8080 # サーバー起動(デフォルトは http://localhost:8080
http-server http-server
# http-server -p 3000 # http-server -p 3000
``` ```
## `http`モジュールを使う場合
* Node.jsの標準機能なので追加ライブラリなしで動作
* 軽量でシンプルな HTTPサーバーをすぐ作れる
* ルーティング機能がなく、URLごとに手動で条件分岐が必要
* ミドルウェア機能(ログ・認証・エラーハンドリング)がない
* 中~大規模開発には向かない(Expressのほうが便利)
```js
const http = require('http'); // httpモジュールをインポート
// サーバーを作成
const httpserver = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' }); // HTTPステータス 200 とヘッダーを設定
res.end('Hello, Node.js Server!'); // クライアントへレスポンスを送信
});
// ポート3000でサーバーを起動
httpserver.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
```
## `Express`を使う場合
xpressはNode.jsの主要なWebフレームワークで
APIサーバーや動的ページの生成にも対応できます。
### インストール方法
```sh
# プロジェクトフォルダを作成して移動
mkdir sample-express-app && cd sample-express-app
# npm 初期化
npm init -y
# Express インストール
npm install express
# `server.js` を作成して、以下を記述
node server.js
```
### サーバースクリプト
`server.js`を作成する
```js
// server.js
const express = require('express');
const app = express();
const port = 3000;
// 静的ファイルを提供
app.use(express.static('public'));
// ルートエンドポイント
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// サーバー起動
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
```