0

I am following a tutorial to create a sign up page using Nodejs and Mysql: https://www.js-tutorials.com/javascript-tutorial/node-js-user-authentication-using-mysql-express-js/

But somehow encountered into the issue below which I could not find any solution. Hope you guys can help. Thanks in advance!

Error log

ReferenceError: C:\Users\User\Desktop\nodejstest\nodejsmysql\webapp\views\index.ejs:18
    16|  
    17|                     <div style="padding-top:30px" class="panel-body" >
 >> 18|                                                                         <% if (message.length > 0) { %>
    19|                                                                                     <div class="alert alert-danger col-sm-12"><%= message %></div>
    20|                                                                         <% } %>
    21|                            

message is not defined

Index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
exports.index = function(req,res){
    var message = '';
    res.render('index',{message: message});
}



router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

Index.ejs

         <div style="padding-top:30px" class="panel-body" >
                                                                <% if (message.length > 0) { %>
                                                                            <div class="alert alert-danger col-sm-12"><%= message %></div>
                                                                <% } %>
jdotdoe
  • 477
  • 2
  • 6
  • 18
  • The variables in EJS or other view engines need to be declared on the .ejs file like: var message = <%= message %>; Take a look here: https://stackoverflow.com/questions/11289793/accessing-ejs-variable-in-javascript-logic – desoares Apr 23 '18 at 15:22

1 Answers1

0
exports.index = function(req,res){
    var message = '';
    res.render('index',{message: message});
}

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

This isn't right.

You've not followed the tutorial to the letter.
To get it working, remove the exports.index bit, and just do:

router.get('/', function(req, res, next) {
  var message = '';
  res.render('index', {message: message});
});

In your example, from the tutorial, you've missed

Step 5: Created a new file routes/index.js

and are just returning { title: 'Express' } to your view - no message

Alex
  • 37,502
  • 51
  • 204
  • 332
  • 1
    Index.js is already there when I install express into the project. What I did was replacing the code with what was shown "/* * GET home page. */ exports.index = function(req, res){ var message = ''; res.render('index',{message: message});" Anyway, your solution works. Thanks. – jdotdoe Apr 23 '18 at 15:41