Ludde
Ludde

Reputation: 3

next() isn't skipping over the rest of the middleware

I'm very much a newbie to the whole express routing logic (and node and js for that matter). But I have problem that I can't seem to trace, but I think I understand the context of it. Well now, that didn't make a lot of sense, here it goes anyway.

I'm trying to skip through middleware conditionally based on data in the req.query and it renders the intended form page fine except for the fact that I get 'Cannot send header twice ...' in the console from the previous middleware, which i thought i skipped.

From what I can gather next() should get me to the next middleware instantly and skip the rest of the block entirely (kind of like how a return kicks you out of a function). Is this not correct?

path: localhost:3000/JohnnyBoy?action=form

    router.get('/:name/', function(req, res, next) {

      if(req.query.action !== 'view') { next(); };

      console.log('Why am I seeing this in the console?');

      res.render('first', { 
        title: req.params.name 
        });
    });

    router.get('/:name/', function(req, res, next) {

        res.render('form', {  
                  title: req.params.name + ' This is a form page', 
                  formFields: fields.userPostFields()
                  });
    });

Upvotes: 0

Views: 673

Answers (1)

Hannan
Hannan

Reputation: 514

You need to put return; after calling next(); only calling next() will not stop execution of the current function.

Replace

if(req.query.action !== 'view') { next(); };

with

if(req.query.action !== 'view') { next(); return;};

Upvotes: 2

Related Questions