I want to set an error message on ejs using flash. But my message is not displaying on the page. If I use the req.session.message, it's working perfectly. When an error occurs, I am redirecting it to another route. I can even access the flash message from there and log it to the console. It displays as an array. But its not displaying on ejs.
if (!catCombo) {
req.flash('message','This category combination doesnot exist.')
throw new Error("Category not found.");
// catch block...............................
} catch (error) {
res.redirect('/admin/add-products')
}
//controller for /admin/add-products
const sendAddProducts = async (req, res) => {
let message = req.flash('message');
req.flash('message','');
console.log(message)
res.render("./admin/addProducts", { message, categories: catSet });
};
Using console.log(message) returns ['This category combination doesnot exists.']
On ejs side:
<% if(locals.message.length){ %>
<div class="alert alert-danger" id="error-message"><%=message[0]%></div>
<% } %>
I entered message[0] since the console was shown as array. I even tried <%=message%\>. If I set the if condition just as locals.message, I can see the red colored div but not the message.
This is how did it on app.js:
const flash = require('connect-flash');
app.use(session({
secret : uuidv4(),
resave : false,
saveUninitialized : true
}));
app.use(flash());