I'm writing my first webb ap with nodejs and express, using ejs templates. now when I'm rendering the html files it all works fine, but when I try to render the files with parameters, it seems like the rendered ejs template can't find the parameters I've sent to it.
here is my file structure :
project/
Views/
index.ejs
login.ejs
public/
all the css files ..
node_modules/
server.js
and here is my server.js :
var express = require('express');
var app = express();
const cookieParser = require('cookie-parser');
const session = require('express-session');
const bodyParser = require('body-parser')
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/Public'));
app.use(cookieParser());
app.use(session({secret: '1234567890QWERTY',resave: false, saveUninitialized: false})); // change the secret to safer one
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function(req, res) {
if (req.session.user == undefined) {
// if user is not logged-in redirect back to login page //
res.render('login');
} else {
console.log(req.session.user);
res.render('index', {username:req.session.user});
}
});
app.get('/login', function(req, res) {
res.render('login');
});
app.listen(8080);
console.log('port: 8080');
and here is my index.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Dashboard</title>
</head>
<body>
<div><%= username %></div>
</body>
</html>
and for some reason whenever I try to access index.ejs, it returnes an error - "username is not defined"
any idea what I'm doing wrong? the examples online looks exactly the same
thanks !
after Fadi Bitar answered this is how my server get event looks like and it's stil won't work:
app.get('/', function(req, res) {
if (req.session.user == undefined) {
// if user is not logged-in redirect back to login page //
res.render('login',{username:req.session.user});
} else {
console.log(req.session.user);
res.render('index', {username:req.session.user});
}
});
// about page
app.get('/login', function(req, res) {
res.render('login',{username:req.session.user});
});
rendercall is the issue, as inres.render('index', {username:'Elion'});- adeneo