23

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.

0

4 Answers 4

24

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!');
});
Sign up to request clarification or add additional context in comments.

3 Comments

this const status = err.status || 500; helped me :) thanks a lot
what if err.status is something invalid (bcoz of typo) like err.status=1 or 24
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.
2

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

1 Comment

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.
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;

1 Comment

Similar to accepted answer, which falls back on default code value 500 using || operator.
0

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.