John Anderson
John Anderson

Reputation: 125

Issues with req.flash within a post request

I check whether or not an email or username is taken. I then use then use flash to send a message to the client using req.flash('messages', 'That username is taken.'); The only problem is I can't call a request command within a function. I can send the message when I put it right after app.post('/signup', function(req, res) { How could I check if a username is taken and then send the req.flash command once it has been determined. I tried to create an if statement but because node is run asynchronously by the time the username is found and the variable is set to true, the if statement has been called. How could I use req.flash to send a message to the client within this post request.

app.post('/signup', function(req, res) {

 var userDetails = User({
    firstname: req.body.firstname,
    username: req.body.username,
    email: req.body.email,
    password: bcrypt.hashSync(req.body.password1, bcrypt.genSaltSync(10))
});

User.findOne({
    $or: [ { 'username': req.body.username}, {'email': req.body.email}]
}, function(err, user) {
    if (user) {
        if(user.username === req.body.username){
          console.log('that username is taken');
          req.flash('messages', 'that username is taken');
        } else {

        }
        if(user.email === req.body.email){
          console.log('that email is already in use');
          req.flash('messages', 'that email is already in use');
        } else {

        }
    } else {
      userDetails.save(function(err) {
        if (err) throw err;
      });
      console.log('change to login')
    }
    if (err) {
        return done(err);
    }
});

res.redirect('/');
});

Upvotes: 0

Views: 697

Answers (1)

CordlessWool
CordlessWool

Reputation: 1530

It should be no problem to call req in a other function if req is defined in a higher level. I am not sure if your flash is session stored, if it not, the reasen why the messages is not flash is your redirection to route.

You redirect to root without waiting to the end of database request. I think you will only redirect if user is found? Include your redirect to the callback function.

Upvotes: 1

Related Questions