Reputation: 587
I have been following this tutorial for my node app to implement authentication: https://scotch.io/tutorials/easy-node-authentication-setup-and-local
The issue I am having is I'm getting this error when running the app: (my code is exacltly how it should be according to the above website).
I tried searching for an answer but the best I could get is adding this function to my server code:
app.use(function(req, res, next){
res.locals.message = req.flash();
next();
});
This loads the application without any errors however, the message does not seem to be displayed in my front-end. Not exactly sure why but Im getting this problem with this project only, I can implement messages without any issues in my other projects.
I've added my github link below but heres bits of my code:
routes.js
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/dashboard',
failureRedirect : '/#contact',
failureFlash : true
}));
passport.js
if (user) {
return done(null, false, req.flash('signupMessage', 'Email already in use!'));
}
index.ejs
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
Github project: https://github.coventry.ac.uk/salmanfazal01/304CEM-Back-End
Upvotes: 1
Views: 789
Reputation: 4073
From the error i think you didn't pass the variable message
correctly to the ejs
view.
So you have 2 solutions
1- In your routes.js
file you need to pass message while rendering index
view, this is how the example you are following is done.
So Change
//GET homepage
app.get('/', function(req, res) {
res.render('index');
});
To
//GET homepage
app.get('/', function(req, res) {
res.render('index' , {message: <your data> });
});
2- using res.locals
and res.flash
which is the solution you found, but you are not actually passing any values in req.flash()
So replace this code
app.use(function(req, res, next){
res.locals.message = req.flash();
next();
});
with
app.use(function(req, res, next){
req.flash("info" , "first message"); //here you add message under type info
req.flash("info" , "second message"); // here you add another message under type info
next();
});
and in your route.js
app.get('/', function(req, res) {
res.render('index' , {message : req.flash("info")}); //set message from req.flash type info
});
//or
app.get('/', function(req, res) {
res.locals.message = req.flash("info"); //set locals.message from req.flash type info
res.render('index');
});
Upvotes: 2