ftdeveloper
ftdeveloper

Reputation: 1093

Node>Expressjs res.render not redirecting

I am developing application with nodejs and express. I have login page. I am posting user data and if there is no user with that data then i want to redirect page. But res.render not working(I added comment where res.render is in my code like "//Redirect if user not found". Have no idea. Here is my code:

var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/fuatblog");
var UserSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String,
    age: Number
}),
    Users = mongoose.model('Users', UserSchema);
app.post('/sessions', function (req, res) {

    console.log(req.body.user.email);
    console.log(req.body.user.password);
    Users.find({
        email: req.body.user.email,
        password: req.body.user.password
    }, function (err, docs) {
        if (! docs.length) {
            // no results...

            console.log('User Not Found');
            //res.status(400);
             //Redirect if user not found
             return res.render(__dirname + "/views/login", {
                    title: 'Giriş',
                    stylesheet: 'login',
                    error: 'Email or password is wrong.'
                });
        }

        console.log('User found');
        req.session.email = docs[0].email;
        console.log(req.session.email);
    });

    return res.redirect('/Management/Index');    
});

Upvotes: 1

Views: 6364

Answers (1)

Krasimir
Krasimir

Reputation: 13529

The .render method which you want to be invoke when the user is not recognized is in async code. This means that the return res.redirect('/Management/Index'); is called once the request reaches your server. But you should do that once you get the result from Users.find. I.e.:

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

    console.log(req.body.user.email);
    console.log(req.body.user.password);
    Users.find({
        email: req.body.user.email,
        password: req.body.user.password
    }, function (err, docs) {
        if (! docs.length) {
            // no results...
            console.log('User Not Found');
            //res.status(400);
             //Redirect if user not found
             return res.render(__dirname + "/views/login", {
                title: 'Giriş',
                stylesheet: 'login',
                error: 'Email or password is wrong.'
            });
        }
        console.log('User found');
        req.session.email = docs[0].email;
        console.log(req.session.email);
        return res.redirect('/Management/Index');
    });

});

Upvotes: 5

Related Questions