Error in middleware: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined

Issue

I am stuck in this problem wherein the console returns an unexpected error code whenever I try to intentionally fail the postman request. The expected results are somehow like this:
Expected error message

but instead, it shows a RangeError something like this:
Unexpected error message
Here is the code for my server.js:

dotenv.config();
const PORT = process.env.PORT || 5000;
const mode = process.env.NODE_ENV;

const app = express();

connectDB();


app.get("/", (req, res) => {
  res.send("API is running...");
});

app.use('/api/products', productRoutes);

app.use((req, res, next) => {
  const error = new Error(`Not Found - ${req.originalUrl}`);
  res.status(404);
  next(error);
});


app.use((err, req, res, next) =>{
  const statusCode = res.statusCode === 200 ? 500 : res.StatusCode;
  res.status(statusCode);
  res.json({
    message: err.message,
    stack: process.env.NODE_ENV === 'production' ? null : err.stack,
  })
});


app.listen(
  PORT,
  console.log(`Server running in ${process.env.NODE_ENV} on port ${PORT}`.cyan.underline)
);

Here is my server.js file:

app.get("/", (req, res) => {
  res.send("API is running...");
});

app.use('/api/products', productRoutes);

app.use((req, res, next) => {
  const error = new Error(`Not Found - ${req.originalUrl}`);
  res.status(404);
  next(error);
});


app.use((err, req, res, next) =>{
  const statusCode = res.statusCode === 200 ? res.StatusCode : 500;
    res.status(statusCode);
    res.json({
      message: err.message,
      stack: process.env.NODE_ENV === 'production' ? null : err.stack,
    })
  });


app.listen(
  PORT,
  console.log(`Server running in ${process.env.NODE_ENV} on port ${PORT}`.cyan.underline)
);

And here is my productRoutes.js file:

const router = express.Router();


export default router;

router.get("/", asyncHandler(async (req, res) => {
    const products = await Product.find({});

    res.json(products);
  }));
router.get("/:id", asyncHandler(async (req, res) => {
    const product = await Product.findById(req.params.id);
    if(product){
        res.json(product);
    }
    else{
        res.status(404)
        throw new Error('Product not found');
    }
  }));

Thanks in advance!

Solution

The error caused by a typo but I would like to explain to the author the meaning of the error and how to debug


You can see in the error message

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined

your server sends a response to the client with the status undefined. It is not a valid status code. See HTTP valid status code here.

You can locate the block where the error occurs when you set the statusCode for the response:

  const statusCode = res.statusCode === 200 ? res.StatusCode : 500;
  res.status(statusCode);

the name of the property is case-sensitive. res.statusCode has value but res.StatusCode is undefined. It should be:

  const statusCode = res.statusCode === 200 ? res.statusCode : 500;
  res.status(statusCode);

Answered By – Đăng Khoa Đinh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published