[Express.js] (node:10151) UnhandledPromiseRejectionWarning: TypeError: res.status is not a function の解決方法

Express.js で (node:10151) UnhandledPromiseRejectionWarning: TypeError: res.status is not a function というエラーの解決方法をご紹介します。

Express.js

前提条件

Node.js, Express.js Version

  • Node.js : version 8.11.3
  • Express.js : version 4.17.1

経緯 – コードレビューでエラーに遭遇

MENTA というサービスで請けている Express.js + MongoDB のコードレビュー で本記事のエラーに遭遇しました。

エラー詳細と解決方法

TypeError: res.status is not a function エラー詳細

  • res.json is not a function
  • (node:10151) UnhandledPromiseRejectionWarning: TypeError: res.status is not a function
res.json is not a function

(node:10151) UnhandledPromiseRejectionWarning: TypeError: res.status is not a function
    at router.get (/path/to/yourapp/routes/api/posts.js:13:16)
    at 
    at process._tickCallback (internal/process/next_tick.js:188:7)
(node:10151) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10151) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

修正前のソースコード

const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator');

const Post = require('../../models/Post');

router.get('/', async (res, req) => {
  try {
    const posts = await Post.find().sort({ date: -1 });
    res.json(posts);
  } catch(err) {
    console.error(err.message);
    return res.status(500).send('Server Error');
  }
});

module.exports = router;

修正後のソースコード diff

引数 req, res を逆に定義していたので res.json is not a function, res.status is not a function エラーとなっていたようでした。

req.json や req.status という method は定義されてないので、そりゃあそうですよね。

diff --git a/routes/api/posts.js b/routes/api/posts.js
index c12c45d..78f94ed 100644
--- a/routes/api/posts.js
+++ b/routes/api/posts.js
@@ -4,7 +4,7 @@ const { check, validationResult } = require('express-validator');
 
 const Post = require('../../models/Post');
 
-router.get('/', async (res, req) => {
+router.get('/', async (req, res) => {
   try {
     const posts = await Post.find().sort({ date: -1 });
     res.json(posts);

以上、Express.js で (node:10151) UnhandledPromiseRejectionWarning: TypeError: res.status is not a function というエラーが出たら req, res が逆になってるのが原因だった、現場からお送りしました。