How to get out of a route in express.js?

I know correctly that I wrapped it entirely in a big if else, because I have several res.render functions.

How can I do something like this that should prevent the rest of the route from completing:

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

OR

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

But both of them execute the rest of the code below them, which have already sent headers.

Now my code is as follows:

 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}); } } 
+4
source share
1 answer

I'm not 100% sure, but if you just want to exit the function after res.render (), I think you can use return . This should interfere with your current function.

A simple AJAX example (I know its client side, but its asynchronous function should behave similarly):

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

If you try to do this in your browser console, you will notice a failure log, but it will stop before the message β€œafter return”.

+3
source

Source: https://habr.com/ru/post/1468834/


All Articles