How about? I am working on a project which I need to pass messages from the server to the client, and I have decided to use the Connect-Flash module. But when the message is passed, the client does not show it. (I'm using the EJS template engine).
This is my Index.ejs
<% if (message.lenght > 0) { %>
<p><%= message%></p>
<% }%>
<br>
<form action="/signup" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col">
<label for="first_name">First name</label>
<input type="text" name="first_name" class="form-control" placeholder="John">
</div>
<div class="col">
<label for="last_name">Last name</label>
<input type="text" name="last_name" class="form-control" placeholder="Doe">
</div>
</div>
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" placeholder="JohnDoe123">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" placeholder="[email protected]">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" placeholder="******">
</div>
<input type="submit" value="Sign in!" class="btn btn-dark btn-lg">
<hr>
<div style="text-align: center">
<p>Already have an account? <a href="/signin">Sign up!</a></p>
<p>or go <a href="/">Home</a></p>
</div>
</form>
This is my Index.js (NodeJS)
app.get('/signup', (req, res) => {
res.render('signup', {message: req.flash('error_msg')});
});
app.post('/signup', (req, res) => {
var first_name = req.body.first_name;
var last_name = req.body.last_name;
var username = req.body.username
var email = req.body.email;
var password = req.body.password;
var newUser = new User({
first_name: first_name,
last_name: last_name,
username: username,
email: email,
password: password
});
User.findOne({username: newUser.username}, (err, username) => {
if (err) throw err;
if (username) {
console.log('Username already taken');
req.flash('error_msg', 'Username already taken!');
}
if (!username) {
User.findOne({email: newUser.email}, (err, email) => {
if (err) throw err;
if (email) {
req.flash('error_msg', 'email already taken!');
console.log(req.flash('error_msg'))
}
if (!email) {
User.createUser(newUser, (err, user) => {
res.redirect('profile');
console.log(user);
})
}
});
}
});
});
It is assumed that the message with the name 'error_msg' when a form is sent and gives an error (If a user or email already exists.). But when the form is sent, not only does the message not appear but it also remains as if waiting for something to happen.