getting RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined in express app
Asked Answered
Q

4

21

I am getting the above error when running the following code in my express app. When I go to localhost:3000/cards.

This is in my cards.js file.

const express = require('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;

router.get('/', (req, res) => {
    res.render('card', {
        prompt: cards[0].question,
        hint: cards[0].hint
    });
});

module.exports = router;

This is the code in my app.js file.

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.set('view engine', 'pug');

const mainRoutes = require('./routes');
const cardRoutes = require('./routes/cards');

app.use(mainRoutes);
app.use('/cards', cardRoutes);

app.use((req, res, next) => {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});

app.use((err, req, res, next) => {
    res.locals.error = err;
    res.status(err.status);
    res.render('error');
});

app.listen(3000, () => {
    console.log('The application is running on localhost:3000!');
});

Any help would be appreciated. Basically, I am trying to incorporate a json file into the express app and it is coming up with this error.

Qualitative answered 10/3, 2018 at 14:22 Comment(3)
I think your cards controllers throws an error that has no status property and therefore express gets an undefined status. Add something like this: const status = err.status || 500; res.status(status);Bobodioulasso
where shall I add that?Qualitative
I added an answerBobodioulasso
B
22

Set a default status in your error handler middleware if error does not contain the property status. In this case we default to error code 500:

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.set('view engine', 'pug');

const mainRoutes = require('./routes');
const cardRoutes = require('./routes/cards');

app.use(mainRoutes);
app.use('/cards', cardRoutes);

app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use((err, req, res, next) => {
  res.locals.error = err;
  //------------------------vvvvvvv added
  const status = err.status || 500;
  res.status(status);
  res.render('error');
});

app.listen(3000, () => {
  console.log('The application is running on localhost:3000!');
});
Bobodioulasso answered 10/3, 2018 at 15:41 Comment(3)
this const status = err.status || 500; helped me :) thanks a lotReifel
what if err.status is something invalid (bcoz of typo) like err.status=1 or 24Kancler
Express will throw an error and send status code 500 + message + stack. If you want to send a custom response, you have 3 options: 1. wrap res.status() in try/catch, 2. use a second error middleware , 3. validate status against the builtin http.STATUS_CODES list.Bobodioulasso
F
2

In My Case this Happened because I haven't provided Authorization in My Request :)

Fredette answered 2/5, 2023 at 20:45 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Flannel
L
1

In my case I was trying to have a fallback value in my custom error class like so:

// apiError.js
class ApiError extends Error {
  constructor(message, source, statusCode) {
    super();
    this.statusCode = statusCode || 500;
    this.message = message;
    this.source = source || 'Unknown';
  }
}

But the actual problem was in the custom error middleware when the response was being send:

// apiErrorHandler.js
import logger from '../util/logger.js';

const apiErrorHandler = function (error, req, res, next) {
  if (error.source) {
    logger.error(`${error.message} ----->  ${error.source}`);
  }

  res.status(error.statusCode ?? 500).json({ // I was missing this ?? 500 as a fallback value
    status: 'error',
    statusCode: `${error.statusCode}` ?? 500,
    stack: error.stack,
  });
};

export default apiErrorHandler;

Ligni answered 5/10, 2023 at 20:30 Comment(1)
Similar to accepted answer, which falls back on default code value 500 using || operator.Hartill
W
0

instead use res.render() if your are using ejs to create the template;

Wira answered 18/5, 2023 at 6:49 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Flannel

© 2022 - 2024 — McMap. All rights reserved.