This is my user Schema.
usermodel.js
const userSchema = new Schema
({
user_name:String,
full_name:String,
user_email:String,
user_pswd:String
});
In my index.js file I am using these middle wares.
index.js
app.use(express.static(path.resolve(__dirname+'/views')));
app.use(session({
secret:'secret-key',
resave:false,
saveUninitialized:true,
}));
app.use(function(req, res, next) {
res.locals.user = req.session.user;
next();
});
I am storing a user session once a user is logged in.
authenticate.js
app.post("/login",urlencodedParser,function(req,res){ //user authentication
user.findOne({user_name:req.body.user_name}) //finding record through username
.then(async function(result){
if(result==null){ //if record not found
alert("no user found");
res.redirect("/#!login")
}
else //if record found
{
const check=await bcrypt.compare(req.body.user_pswd,result.user_pswd); //comparing the encrypted password
if(check)
{
req.session.user=result; //storing the user in session
alert("login successful");
res.redirect('/');
}
else
{
alert("incorrect password");
res.redirect("/#!login");
}
}
})
})
And rendering a different file on "/", based on whether a user is logged in or not.
index.js
app.get("/",function(req,res) //initially loading index file
{
if(!res.locals.user) //if the user is not logged in
{
app.use(express.static(path.resolve(__dirname+'/views/landing')));
res.render("./landing/index.html");
}
else{
app.use(express.static(path.resolve(__dirname+'/views/service')));
res.render("./service/index.ejs");
}
});
I am successfully able to access the user.user_name in my index.ejs.
index.ejs
<html lang="en">
<head>
<script src="../lib/angular.js"></script>
<script src="../lib/angular-route.js"></script>
<script defer src="./controller/app.js"></script>
</head>
<body ng-app="mod2" ng-controller="ctrl2">
<h1>Hi <%=user.user_name%></h1>
<div ng-view></div>
</body>
</html>
This is my Angular JS routing file. I want to call welcome.ejs on /
app.js
var obj= angular.module('mod2',['ngRoute']);
obj.config(function($routeProvider)
{
$routeProvider
.when('/',{
templateUrl:"./partials/welcome.ejs"
})
.when('/chat',{
templateUrl:"./partials/chat.ejs"
})
.when('/news',{
templateUrl:"./partials/news.ejs"
});
});
But when I am trying to access the user.user_name in my welcome.ejs I am unable to do so, I read that res.locals is used to load data to all my EJS templates, but that is not happening.
welcome.ejs
<html lang="en">
<body>
<h1>Welcome <%=user.user_name%></h1>
</body>
</html>
This is not working, it is not loading the data, what am I missing? Thank You.
Aucun commentaire:
Enregistrer un commentaire