I'm building an express app where when a user completes a form; if successful, they will see an alert confirming their submission.
In my server.js file, I am declaring
var cookieParser = require("cookie-parser"),
session = require("express-session"),
flash = require("connect-flash"),
app = express();
Followed by:
app.use(cookieParser("keyboard cat"));
app.use(session({
cookie: { maxAge: 60000 },
secret: "keyboard cat"
}));
app.use(flash());
require("./server/config/routes.js")(app);`
My routes file:
app.get("/", function(req, res){
res.render("index", { message: req.flash("success") });
});
app.post("/sendMsg", function(req, res){
mainController.sendMsg(req, res);
});
app.get("/sentSuccess", function(req, res){
req.flash("success", "Thanks!");
res.redirect("/");
});
Finally in my main.js file for jquery calls (I'm using SweetAlert for alert styling):
$(document).ready(function(){
if(message){
var frm = document.getElementsByName('msgForm')[0];
swal({
title: "Sweet!",
text: "Thanks",
imageUrl: "javascripts/sweetalert/thumbs-up.jpg"
});
frm.reset();
}
});
The issue I'm hitting is Uncaught ReferenceError: message is not defined
on the client-side console. I've read through https://www.npmjs.com/package/connect-flash and looked through the example at https://github.com/jaredhanson/connect-flash/tree/master/examples/express3 but I'm not sure why message is not being passed back.
Maybe, the problem is with the way your code is trying to access the message
variable. As @Pushkin said message
will be passed to the view and can't be as such referenced by the javascript.
You can try this (in case you are using jade as view engine)
if message
.script
// your javascript or function()
So finally code looks like :
if message
.script
var frm = document.getElementsByName('msgForm')[0];
swal({
title: "Sweet!",
text: "Thanks",
imageUrl: "javascripts/sweetalert/thumbs-up.jpg"
});
frm.reset();
Now you will be able to access the message
variable.
In case if using ejs
the syntax is almost similar
<% if (message) { %>
// Do something here..
<% } %>