David Gatti David Gatti - 11 days ago 6
Node.js Question

NodeJS/ExpressJS - Issue on handling multiple Middlewares inside a route

I have the following situation. I have a route that reacts to post requests. Inside the route I thought it would be nice to split the code in to modules, to better organize the project that I'm working on.

The solution that I came up, is not ideal because if there is async code, then the route will go till the

next()
statement, and respond with a 404.

Where, I would like the response to be coming from the modules, and only execute
next()
, if the if states fails. To let the user know that the URL provided is wrong.

I would like to have the same behavior of a middleware, but I can't figure out if it is even possible to have a middleware inside a route.

Questions



Is it possible?

Code





let express = require('express');

let router = express.Router();

router.post('/:action/:channel_id', function(req, res, next) {

if(req.params.action == 'default')
{
require('./alerts/default.js')(req, res);
}

if(req.params.action == 'error')
{
require('./alerts/error.js')(req, res);
}

if(req.params.action == 'warning')
{
require('./alerts/warning.js')(req, res);
}

next();

});

module.exports = router;

Answer

You can either use if..else or switch..case as below.

Method 1: (using if..else)

let express = require('express');

let router = express.Router();

router.post('/:action/:channel_id', function(req, res, next) {

    if(req.params.action == 'default')
    {
        require('./alerts/default.js')(req, res);
    }
    else if(req.params.action == 'error')
    {
        require('./alerts/error.js')(req, res);
    }
    else if(req.params.action == 'warning')
    {
        require('./alerts/warning.js')(req, res);
    }
    else {
      res.status(404).send('Url does not exists');
      //next();
    }

});

module.exports = router;

Method 2: (using switch..case)

let express = require('express');

let router = express.Router();

router.post('/:action/:channel_id', function(req, res, next) {

    switch (req.params.action) {
       case 'default':
         require('./alerts/default.js')(req, res);
         break;
       case 'error':
         require('./alerts/error.js')(req, res);
         break;
       case 'warning':
         require('./alerts/warning.js')(req, res);
         break;
       default:
         res.status(404).send('Url does not exists');
         // next();
         break;
    }
});

module.exports = router;