'Login and Register not working node.js MongoDB

my app.js not working as i think. so, after i register for a new one, it will send to my MongoDB and take me directly to the page2 but it is taking back to the home page and when i type in and click on login, it will have the error "This site can’t be reached" on localhost:8080/processLogin. im not sure how to fix them. i think errors are on function checkLogin(req, res, user, password) and app.post('/processReg', function(req, res)

app.js

var express = require('express'),
    handlebars = require('express-handlebars').create({ defaultLayout: 'main' }),
    cookieParser = require('cookie-parser'),
    sessions = require('express-session'),
    bodyParser = require('body-parser'),
    https = require('https'),
    fs = require('fs'),
    md5 = require('md5'),
    mongoose = require('mongoose'),
    credentials = require('./credentials'),
    Users = require('./models/uCredentials.js');
// load env variables
const dotenv = require("dotenv");
dotenv.config();

var app = express();
//db connection
mongoose
    .connect(process.env.MONGO_URI, {
        useUnifiedTopology: true,
        useNewUrlParser: true,
    })
    .then(() => console.log("DB Connected"));

mongoose.connection.on("error", (err) => {
    console.log(`DB connection error: ${err.message}`);
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser(credentials.cookieSecret));
app.use(sessions({
    resave: true,
    saveUninitialized: false,
    secret: credentials.cookieSecret,
    cookie: { maxAge: 3600000 },
}));

app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

app.set('port', process.env.PORT || 3100);

app.get('/', function(req, res) {
    res.render('login');
});

function checklogin(req, res, user, password) {
    //implementation of this function
    Users.findOne({ uname: user }, function(err, user) {
        if (err) {
            console.log(err);
            res.send({ 'message': 'Login successfully!' });
        } else {
            res.send({ 'message': 'Username or password do not match our records. Please try again or register if you are a new user!' });
        }

    });
};

app.post('/processLogin', function(req, res) {
    //Determine if user is registering
    if (req.body.buttonVar == 'login') {
        checklogin(req, res, req.body.uname.trim(), req.body.pword.trim())
    } else {
        res.redirect(303, 'register');
    }
});

app.post('/processReg', function(req, res) {
    //implement this end point
    if (req.body.pword.trim() == req.body.pword2.trim()) {
        const user = new Users({ uname: req.body.uname, pass: req.body.pword });
        console.log('Creating new user ', req.body);
        user.save((err, toDB) => {
            if (err) {
                return res.status(400).json({ error: err });
            }
            res.status(200).json({ user: toDB });
        });
        res.redirect(303, 'page2');
    } else {
        res.render('register', { message: 'The two passwords are not the same !' });
    }

});

app.get('/home', function(req, res) {
    if (req.session.userName) {
        res.render('home');
    } else {
        res.render('login', { message: 'Please login to access the home page' });
    }
});

app.get('/page2', function(req, res) {
    if (req.session.userName) {
        res.render('page2');
    } else {
        res.render('login', { message: 'Please login to access the second page' });
    }
});

app.get('/register', function(req, res) {
    res.render('register');
});

app.get('/logout', function(req, res) {
    delete req.session.userName;
    res.redirect(303, '/');
});


app.listen(app.get('port'), function() {
    console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate');
});

process.on('unhandledRejection', error => {
    // Will print "unhandledRejection err is not defined"
    console.log('unhandledRejection', error.message);
});


Solution 1:[1]

callback logic for findOne query is wrong. check this out async/await For checkLoging function try using this:

async function checklogin(req, res, user, password) {
            try {
                //implementation of this function
                const user = await Users.findOne({ uname: user }).exec();
                if (!user) {
                   res.send({ 'message': 'Username or password do not match our records. Please try again or register if you are a new user!' });
                }
                res.send({ 'message': 'Login successfully!' });
            } catch (err) {
                console.log(err.message)
            }
};

If you don't want to use Async/await (which I recomend for mongodb queries) you can use this:

function checklogin(req, res, user, password) {
    //implementation of this function
    Users.findOne({ uname: user }, function(err, user) {
        if (err) {
            console.log(err);
            res.send({ 'message': 'Username or password do not match our records. Please try again or register if you are a new user!' });
        }
        res.send({ 'message': 'Login successfully!' });
    });
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 D.J