Dail
Dail

Reputation: 4606

How to render ONLY one view?

I'm using Node.JS and Express web framework, I have a problem with the res.render()

I have this function:

exports.init = function(){

    return function(req, res, next) {   

        /* FORM CONTACT */
        if (req.body.contact){                      

            model.validateContact(function(e){              
                if (err) res.render('contacts', {'error': err})

                else {
                    model.sendContact(function(err){                                                
                        if (err) 
                            res.render('contacts', {'error': err})                              
                        else
                            res.redirect('/success')                                                        
                    })                                  
                }               
            })      

        }
        /* CONTACT */       

        res.render('contacts')
        console.log('after')
    }

}

Here I have a problem because res.render doesn't exist from the init function(I refer to the res.render inside the inner functions (validateCOntact and sendContact) so the last res.render('contacts') will be always executed.

Why the script is continuing its process if I render a page? How is it possible that I can do res.render() more then one time?

Thank you

Upvotes: 0

Views: 179

Answers (3)

alessioalex
alessioalex

Reputation: 63663

Try this:

exports.init = function() {

  return function(req, res, next) {
    /* FORM CONTACT */
    if (req.body.contact){
      model.validateContact(function(e) {
        if (err) {
          res.render('contacts', {'error': err});
        } else {
          model.sendContact(function(err) {
            if (err) {
              res.render('contacts', {'error': err});
            } else {
              res.redirect('/success');
            }
          });
        }
      });
    } else {
      /* CONTACT */
      res.render('contacts');
      console.log('after');
    }
  }
}

Upvotes: 1

alessioalex
alessioalex

Reputation: 63663

Each time you do res.redirect or res.render you should return, because if you don't you'll get the "Can't sent headers after.." error, since you'll be rendering another view.

Upvotes: 0

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

Just return after calling res.render(). ex:

if (err){
    res.render('contacts', {'error': err})
    return
}

Upvotes: 0

Related Questions