LoginSignup
1
0

More than 3 years have passed since last update.

Express(Node.js)で対応していないメソッドに対して405を返す

Posted at

はじめに

ExpressでAPIを実装する際に、ルーティングとしては定義されているが、メソッドが対応していない場合に405エラーを正しく返す方法を考えます。

APIの実装

APIの実装を下記のように行います。
この場合、http://localhost:3000/api/userにGETを行うとgetHandlerが実行されますが、同URLにPOSTを行うと404エラーとなってしまいます。

const express = require('express');
const app = express();

app.get('/api/user', getHandler);

const port = 3000;

app.listen(port, () => {
    console.log(`server started on port ${port}`);
}); 

405エラーを正しく返す

405エラーを返すだけの関数methodNotAllowedを実装して、下記のようにallのハンドラーとして指定します。
こうするとGETの場合はgetHandlerが実行され、それ以外のメソッドの場合は405エラーを返すようになります。

const express = require('express');
const app = express();

const methodNotAllowed = (req, res, next) => res.status(405).send();

app.route('/api/user')
.get(getHandler)
.all(methodNotAllowed);

const port = 3000;

app.listen(port, () => {
    console.log(`server started on port ${port}`);
}); 
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