Deep Vora
Deep Vora

Reputation: 328

Express router bypasses middleware

I am trying to create middleware to handle the response that are next()ed from the routes, but it bypasses route.use and throws 404

const router = require('express').Router();
const { errorResponse, successResponse, redirectResponse } = require('./test');

const errorResponse = (err, req, res, next) => {
    next(Boom.notFound());
};

const successResponse = (err, req, res, next) => {
    res.locals.res = {
        data: {
            hello: 'world'
        }
    };
    next();
};

const redirectResponse = (err, req, res, next) => {
    res.locals.res = {
        meta: {
            redirect: true
        }
    };
    next();
};

module.exports = (app) => {
    /**
     * Test Routes
     */
    router.get('/successTest', successResponse);
    router.get('/errorTest', errorResponse);
    router.get('/redirectTest', redirectResponse);

    router
        .use((err, req, res, next) => {
            console.log('successHandler');
            next();
        })
        .use((err, req, res, next) => {
            console.log('redirectHandler');
            next();
        })
        .use((err, req, res, next) => {
            console.log('errorHandler');
            res.status(200).json({});
        });
        // does not go to any of the middlewares and gives out 404
        // from digging in i found that err param is not err but is req
    app.use('/v1', router);
};

Thanks for helping

Upvotes: 0

Views: 124

Answers (1)

noctifer20
noctifer20

Reputation: 198

Take a look at Express.js Error-handling middleware documentation.

Basically it says that middleware with 4 arguments like

app.use(function (err, req, res, next) {
 console.error(err.stack)
 res.status(500).send('Something broke!')
})

interpreted as middleware to handle errors. It means that it won't act like regular middleware.

For example:

app.get('/1',
  (err, req, res, next) => {
    // will not be outputted in console
    console.log('got here');
    next();
  },
  (req, res) => {
    res.send('Hello World!');
  });
app.get('/2',
  (req, res, next) => {
    console.log('got here');
    next();
  },
  (req, res) => {
    res.send('Hello World!');
  });

Upvotes: 1

Related Questions