2023.09.24
TypeScript × express でローカルサーバーを立ち上げる【その2: ルーターを追加して特定のメソッドを許可する】

この記事でのゴール
任意のパスで任意のHTTPメソッドを許可する
前提条件
以下をインストール済みであること
- Node.js(18系)
- npm または yarn
使うもの
ファイル構成
├── package.json
├── src
│ └── index.ts // このファイルを使って実行
└── yarn.lock
やること
ほぼ前回の記事の続きです。
- パスを追加する
- 1で追加したパスにGETメソッドを許可するコードを追加する
- サーバーを起動してcurlコマンドでリクエストまたはブラウザからアクセス
1. パスを追加する
src/index.ts
で、まずは /posts/:id
でアクセスできるようパスを追加
import express, { Request, Response } from 'express'
const app = express()
const router = express.Router()
const PORT = 3000
router.use('/posts/:id', (req: Request, res: Response, next) => {
res.statusCode = 200
res.send('hello world :)')
})
app.use('/', router)
app.listen(PORT)
この状態だとGET以外でも hello world :)
がレスポンスとして返されます。
例
curl -X POST http://localhost:3000/posts/1
Response
hello world :)
2. GETメソッド以外でリクエストしたら405を返す
import express, { Request, Response } from 'express'
const app = express()
const router = express.Router()
const PORT = 3000
const ERROR_CODES = {
methodNotAllowed: 'method-not-allowed'
} as const
type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES]
interface ErrorResponse {
code: ErrorCode
message: string
}
router.use('/posts/:id', (req: Request, res: Response, next) => {
if (req.method !== 'GET') {
const errorResponse: ErrorResponse = { code: ERROR_CODES.methodNotAllowed, message: 'Method Not Allowed.' }
res.status(405).send(errorResponse)
}
res.statusCode = 200
res.send('hello world :)')
})
app.use('/', router)
app.listen(PORT)
3. サーバーを起動して追加したパスにリクエスト
package.json
に scripts
を追加
"scripts": {
"start": "ts-node ./src/index.ts"
}
package.json
がルートにある状態でコマンドを実行
yarn start
ブラウザのURLに http://localhost:3000/posts/1
を入れると hello world :)
が表示されます。
尚、POSTでリクエストした場合
curl -X POST http://localhost:3000/posts/1
405ステータスコードで、以下のようなレスポンスが返されます。
{"code":"method-not-allowed","message":"Method Not Allowed."}