Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8902

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

$
0
0
はじめに 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}`); });

Viewing all articles
Browse latest Browse all 8902

Trending Articles