js-common-code/docs/httpserver.md
2025-03-21 00:03:36 +09:00

87 lines
2.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [Node.js]NodeでHttpサーバーを起動及び構築する方法
## `http-server`を使う場合
http-serverはNode.js のシンプルな静的ファイルサーバーです。
インストールすれば簡単にローカルでファイルをホスティングできます。
```sh
# http-server をグローバルインストール(初回のみ)
npm install -g http-server
# ファイルがあるディレクトリへ移動
cd src/front
# サーバー起動(デフォルトは http://localhost:8080
http-server
# 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}`);
});
```