Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a route in express.js?

Tags:

node.js

Right know i wrap it whole in a big if else statement because i have multiple res.render functions.

How can i do something like this, which should prevent the rest of the route to be executed:

if(req.params.url === undefined){
    res.render('layout');
    return;
}

OR:

if(req.params.url === undefined){
    res.render('layout');
    next();
}

But both of the execute the rest of the code below them, which cause Headers already sent.

Right now my code looks like this:

exports.activate = function(req, res){
    var hash = req.params.hash;

    if(hash === undefined){
        res.render('activation');
        next();
    } else {
           // Do stuff with hash
           res.render('activateOne', {hash: hash});
    }

}
like image 833
Kevin Simper Avatar asked Oct 22 '22 15:10

Kevin Simper


1 Answers

I'm not 100% sure of this, but if you just want to exit the function after your res.render() I think you can use return. This should prevent the rest of your current function from executing.

A simple AJAX example (I know its client side, but its an async function and should behave similar):

$.ajax({
   url: 'www.google.com',
   type: 'POST',
   error: function () {
      console.log('failure');
      return 0;
      console.log('after return');
   }
})

If you try to execute this in your browsers console, you will note the 'failure' log, however it will stop before the 'after return' message.

like image 139
Nick Mitchinson Avatar answered Oct 27 '22 11:10

Nick Mitchinson