1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptでNode.jsの組み込みhttpモジュールを使ってHTTPサーバーを作る

Posted at

はじめに

Node.jsの組み込みhttpモジュールを使ってTypeScriptで簡単なサーバーを作る機会があったので、紹介します。

Expressなどのフレームワークを使わずに、軽量なHTTPサーバーを構築したい場合に便利です。

実装例

以下は、URLパスに応じて異なるステータスコードとJSONレスポンスを返すシンプルなHTTPサーバーの実装例です。

import { createServer, IncomingMessage, ServerResponse } from 'http';

const PORT = 8080;

const server = createServer((req: IncomingMessage, res: ServerResponse) => {
  res.setHeader('Content-Type', 'application/json');

  if (req.url === '/success') {
    res.statusCode = 200;
    res.end(JSON.stringify({ message: 'OK', status: 200 }));
  } else if (req.url === '/error') {
    res.statusCode = 500;
    res.end(JSON.stringify({ message: 'Internal Server Error', status: 500 }));
  } else {
    res.statusCode = 404;
    res.end(JSON.stringify({ message: 'Not Found', status: 404 }));
  }
});

server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

動作確認

サーバーを起動後、以下のコマンドで動作確認できます:

# 成功レスポンス
curl http://localhost:8080/success

# エラーレスポンス
curl http://localhost:8080/error

# 404レスポンス
curl http://localhost:8080/other

環境

  • Node.js: v20.15.1
  • TypeScript: 5.5.3
  • @types/node: 20.14.10
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?