ejs template variable is not defined on page load and errors

26,282

Solution 1

You could use a value in the error property that won't get through into the if:

res.render('registration', {error: false});

Solution 2

You can do that check in three ways :-

  • Using the method suggested by Amit :

res.render('registration', {error: false});

  • Check to see if error exists like this :

<% if( typeof(error) =="undefined")%> //checks the type of variable

  • You can see if the variable error exists by accessing the locals object like this :

<% if(locals.error) %>

Solution 3

The following code explains a working example:

<% if (typeof error ='object' && error) { %>
    <li><%= error %></li>  
<% } %>

Solution 4

I was facing the same problem and you can try it in two different ways.

  1. Pass false to error on get from js file like below.
router.get('/login', function(req, res, next) {
    res.render('login', { title: 'Please login',  error: false });
});
  1. Another way is to handle it in ejs file, here you can check that error is passing from method call or not, like below.
<% if (typeof error != "undefined" && error.username) {  %>
    <p><%= error.username.msg %></p>
<%} %>
Share:
26,282
Mike Rifgin
Author by

Mike Rifgin

Updated on December 16, 2021

Comments

  • Mike Rifgin
    Mike Rifgin over 1 year

    I have a form submitting to an express app:

    app.post('/myform', function (req, res) {
        var content = new registration(req.body);
        content.save(function(errObj){
        if(errObj){
            res.render('registration',{error: errObj});
        } else {
            res.render('thankyou');
        }
    });
    

    If there are any errors in saving the form data to mongoDb I want to display those errors at the top of the form so I'm passing the error object back to the ejs template:

    <% if (error) { %>
       <li><%= error %></li>  
    <% } %>
    

    But when I initially load the page and there are no errors yet (because the form has not been submitted) I'm receiving an error on the page and the form is not rendered:

    error is not defined
    

    How can I get around this?