Bolboa Bolboa - 5 months ago 33
Node.js Question

How to send user to another page after login (node js)

I have the following code that checks to see if a user exists in a database...

router.post('/', function (req, res) {

User.findOne({
username: req.body.log_username,
password: req.body.log_password
}, function (err, docs) {
if (docs.length !== 0) {
console.log("user exists");

}
else {
console.log("no exist");
}
});

});


I have a home page that I want to send the user to if the login was a success. What should I put in the
if
statement to send the use to another page, in this case,
home.js
.
home.js
has the following code in it...

var express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
res.render('home', { title: 'Express' });
});

module.exports = router;

Answer

You need to redirect the user to main page. res.redirect('path')

Reference : http://expressjs.com/en/4x/api.html#res.redirect

router.post('/', function (req, res) {

    User.findOne({
        username: req.body.log_username,
        password: req.body.log_password
    }, function (err, docs) {
        if (docs.length !== 0) {
            console.log("user exists");
            res.redirect('/'); // main page url
        }
        else {
            console.log("no exist");
            res.redirect('/login');
        }
    });

});
Comments