[Express.js] How to Fix (node:10151) UnhandledPromiseRejectionWarning: TypeError: res.status is not a function
I’ll introduce how to fix the error (node:10151) UnhandledPromiseRejectionWarning: TypeError: res.status is not a function in Express.js.
I encountered this error during Express.js + MongoDB code review I’m handling through MENTA service.
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;
The arguments req and res were defined in reverse order, which was causing the res.json is not a function and res.status is not a function errors.
Since req.json and req.status methods are not defined, it makes perfect sense.
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);
That’s all from the Gemba.