I have read other post in StackOverflow about Bcrypt compare method returning false always. But I can not solve mine with the suggested answers. I am about to give up using Bcrypt. Could someone please point out what is wrong in my code. I am simply storing registration data with encrypted password in users array and after login attempt I am trying to compare the user-input password with the saved one in users array. No matter what I am doing the compare() method is returning false. PLease point out my mistake. I am providing the server.js file and passport.js file here.
The server.js -->
const express = require("express")
const bcrypt = require("bcrypt")
const initializePassport = require("./passport.js")
const flash = require("express-flash")
const session = require("express-session")
const { application } = require("express")
const passport = require("passport")
const server = express()
const users = []
const salt = bcrypt.genSaltSync(10);
initializePassport(
passport,
email => users.find(u => u.email === email),
id => users.find(u => u.id === id)
)
// below line of code is to get the form data in req.body
server.use(express.urlencoded({ extended: false }))
server.use(flash())
server.use(session({
secret: "1234",
resave: false, // we want to resave the session variable if nothing is changed
saveUninitialized: false
}))
server.use(passport.initialize())
server.use(passport.session())
async function main() {
const PORT = 8080
server.listen(PORT, function() {
console.log(`Server started on port ${PORT}...`)
})
}
server.get('/', async(req, res) => {
res.render("index.ejs")
})
server.get('/login', (req, res) => {
res.render('login.ejs')
})
server.post('/login', passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
}))
server.get('/registration', (req, res) => {
res.render('registration.ejs')
})
server.post('/registration', async(req, res) => {
const { firstName, lastName, email, password } = req.body
await bcrypt.hash(password.toString(), salt)
.then((hashedPassword) => {
// Store the hashed password in the users array
users.push({
id: Date.now().toString(),
email: email,
password: hashedPassword,
firstName: firstName,
lastName: lastName
})
console.log(users)
res.redirect("/login")
})
.catch((error) => {
console.log(error);
});
})
main();
The passport.js file -->
const LocalStrategy = require("passport-local").Strategy
const bcrypt = require("bcrypt")
function initialize(passport, getUserByEmail, getUserById) {
// Function to authenticate users
const authenticateUsers = async(email, password, done) => {
// Get users by email
const user = await getUserByEmail(email)
console.log("THE Password BEFORE COMPARISON --> " + password)
console.log(user)
if (user == null) {
console.log("user null;;;lllll")
return done(null, false, { message: "User is not registered" })
}
bcrypt.compare(password.toString().trim(), user.password, function(err, result) {
console.log("THE PASSWORD AFTER COMPARISON --> " + password)
console.log(user)
if (err) {
console.log(err)
}
if (result == true) {
console.log("PASSWORD MATCHES")
} else {
console.log("DOESNOT MATCH")
}
})
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUsers))
passport.serializeUser((user, done) => {
console.log(`---------------> Serialize User`)
console.log(user)
done(null, user.id)
})
passport.deserializeUser((id, done) => {
console.log("---------> Deserialize Id")
console.log(id)
return done(null, getUserById(id))
})
}
module.exports = initialize
And here is the registration view
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Registration</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<style>
.main {
background-color: #EAF7FF;
width: 100%;
height: 100vh;
margin: auto;
}
.form-container {
background-color: rgb(255, 255, 255);
max-width: 500px;
margin: 0 auto;
padding: 30px;
border: 1px solid #ccc;
border-radius: 10px;
box-shadow: 0 0 10px #ccc;
}
.btn {
background-color: #4F95FF;
border-radius: 14px;
}
</style>
</head>
<body>
<div class="main">
<div class="form-container">
<form action="/registration" method="POST">
<% if(messages.error) { %>
<div class="alert alert-danger" role="alert">
<strong><%= messages.error %></strong>
</div>
<% } %>
<h2 class="text-center">Register</h2>
<div class="form-group">
<input type="text" name="firstName" class="form-control" id="firstName" placeholder="First name">
</div>
<div class="form-group">
<input type="text" name="lastName" class="form-control" id="lastName" placeholder="Last name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" id="password" placeholder="Confirm Password">
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary btn-rounded btn-lg">Create Account</button>
</div>
<div class="text-center">
<p>Already have an account?
<a href="login">Login</p>
</div>
</form>
</div>
</div>
</body>
</html>
Actually I found the issue. Its in frontend. I used same "name" and "id" attribute for password and confirmPassword field. So req.body.password was appending password from both field.
Related
I can not get the table to display when the search button is clicked using JavaScript. not sure why, can someone please help? Code snippets below and actual repos and site linked below as well.
Here is GitHub repo so that you can see the entire site if you wish:
https://github.com/Chad1515/pets-r-us
Here is the site deployed on heroku:
https://oneal-pets-r-us.herokuapp.com/
//trying to display appointments on my appointment page
app.get('/my-appointments', (req, res) => {
res.render('my-appointments', {
title: 'My Appointments',
})
})
app.get('/api/appointments/:email', async(req, res, next) => {
Appointment.find({'email': req.params.email}, function(err, appointments) {
if (err) {
console.log(err);
next(err);
} else {
res.json(Appointment);
}
})
})
<!--form inputs and card for appointments-->
<section>
<div class="card2">
<p>My Appointments</p>
<hr class="third">
<div class="form">
<div class="form-field">
<label for="email">email</label><br />
<input type="text" class="input" name="email" id="email" required>
</div>
<div class="form-field">
<input type="submit" value="Search" id="search" class="btn">
</div>
<div id="appointments"></div>
</div>
</div>
</section>
<script>
document.getElementById('search').onclick = function() {
const email = document.getElementById('email').value;
fetch('/api/appointments/' + email)
.then(res => res.json())
.then(data => {
let tableString = `<br /><br /><h4 style="font-size: 32px; text-align: center; padding-bottom: 10px;">
My Appointments</h4><table id="appointments" class="table"><tr><th>First name</th><th>Last name</th><th>Email</th><th>Service</th></tr>`;
for (let appointment of data) {
tableString += `<tr><td>${appointment.firstName}</td><td>${appointment.lastName}</td><td>${appointment.email}</td><td>${appointment.service}</td></tr>`;
}
tableString += `</table>`;
document.getElementById('appointments').innerHTML = tableString;
});
}
</script>
It looks like you are responding with the Appointment model object instead of the appointments documents. Try this instead:
app.get('/api/appointments/:email', async(req, res, next) => {
Appointment.find({'email': req.params.email}, function(err, appointments) {
if (err) {
console.log(err);
next(err);
} else {
// Respond with the appointments documents instead of the Appointment model
res.json(appointments);
}
})
})
I'm very new to web development, and now I'm trying to build a login page which uses HTML, CSS and Javascript for the website, and MongoDB database to store the data received from the user. I followed a few tutorials on YouTube, but for some reasons the data cannot be posted.
Here are the codes that I have so far:
(Javascript)
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded( {extended: true}));
mongoose.connect("mongodb+srv://cs196:cs196#userdata.sn7wv.mongodb.net/cs196", { userNewUrlParser: true}, {useUnifiedTopology: true} );
// create a data schema
const notesSchemaCreate = {
username: String,
email: String,
password: String,
confirm_password: String
}
const Note = mongoose.model("NoteCreate", notesSchemaCreate)
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
})
app.post("/", function(req, res) {
let newNote = new Note({
username: req.body.username,
email: req.body.email,
password: req.body.password,
confirm_password: req.body.confirm_password
});
newNote.save();
})
app.listen(3000, function() {
console.log("server is running on 3000")
})
(And here are the HTML codes)
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<title>Login Site</title>
<link rel="stylesheet" href="./main.css">
</head>
<body>
<div class="container">
<!-- Create an account -->
<form class="form form--hidden" id="createAccount" method= "post" action="/">
<h1 class="form__title">Create Account</h1>
<div class="form__message form__message--error"></div>
<div class="form__input-group">
<input type="text" id="signupUsername" class="form__input" name="username" autofocus placeholder="Username">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="text" class="form__input" name= "email" autofocus placeholder="Email Address">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="password" class="form__input" name= "password" autofocus placeholder="Password">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="password" class="form__input" name= "confirm_password" autofocus placeholder="Confirm Password">
<div class="form__input-error-message"></div>
</div>
<button class="form__button" type="submit">Continue</button>
<p class="form__text">
<a class="form__link" href="./" id="linkLogin">Already have an account? Sign In</a>
</p>
</form>
</div>
</body>
I'm trying out the results using localhost:3000, which looks like this:
The result simply gave me cannot POST / in a new page.
Please let me know if there might be something off with my MongoDB setting, or if you want to see how the setting is right now, since I don't know what parts to show you guys and I don't want to make this post incredibly long.
Thanks in advance for anyone who can help me out with this! And I apologize in advance if my codes or this post is formatted horribly.
Each endpoint function must end the request-response cycle by sending a response ( res.send(), res.json(), res.end(), etc).
model.create() is asyncronous. Mark your function as async
So the solution would be:
app.post("/", async(req, res) => {
try {
const newUser = await Note.create({
username: req.body.username,
email: req.body.email,
password: req.body.password,
confirm_password: req.body.confirm_password
});
res.json({status: "success", message: "user created successfully", user: newUser})
} catch(error) {
res.json({status: "fail", message: error.message ? error.message : "could not create user"})
}
})
P.S: never expose your secret(mongo_uri, stripe_key, etc.) keys public.
I have the code below for a login system with nodejs express and mySQL. The registration and the login services work, but the logout doesn't. Also, how can I restrict my pages from a normal user, in order only an admin can access them. File structure:
Here is the code:
app.js
onst path = require('path');
const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const dotenv = require('dotenv');
const cookieParser = require('cookie-parser');
dotenv.config({ path: './.env' });
var flash = require('express-flash');
var session = require("express-session");
const app = express();
// DB connection
const connection = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
connection.connect(function(error) {
if (!!error) console.log(error);
else console.log('CONGRATS! Database Connected! (app)');
});
//set views file
app.set('views', path.join(__dirname, 'views'));
//set public file
app.use(express.static(__dirname + '/public'));
//set view engine
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.urlencoded({ extended: false })); //instead of false
const routes = require('./server/routes/index');
app.use(session({
cookie: { maxAge: 60000 },
store: new session.MemoryStore,
saveUninitialized: true,
resave: true,
secret: 'mysecret'
}))
app.use(flash());
// Defining Routes
app.use('/', routes);
app.use('/auth', require('./server/routes/auth'));
// Server Listening
app.listen(3000, () => {
console.log('Server is running at port 3000');
});
routes/auth.js
const express = require('express');
const authController = require('../controllers/auth');
const auth_router = express.Router();
auth_router.post('/register', authController.register)
auth_router.post('/login', authController.login);
module.exports = auth_router;
routes/index.js
var express = require('express');
const jwt = require('jsonwebtoken');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(req.session);
console.log(req.headers.cookie);
res.render('home', {
title: 'Express',
loggedIn: req.headers.cookie
});
});
router.get('/register', (req, res) => {
res.render('register');
});
router.get('/login', (req, res) => {
res.render('login');
});
router.get('/logout', function(req, res) {
req.session.destroy();
res.redirect('/');
})
controllers/auth.js
const mysql = require("mysql");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
var flash = require('express-flash');
const db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
exports.login = async(req, res) => {
try {
const { username, password } = req.body;
if (!username || !password) {
req.flash('danger', 'Please provide username and password!');
return res.status(400).render('login');
}
db.query('SELECT * FROM users WHERE username = ?', [username], async(error, results) => {
console.log(results);
if (!results || !(await bcrypt.compare(password, results[0].password))) {
req.flash('danger', 'Username or password is incorrect!');
res.status(401).render('login')
} else {
const id = results[0].user_id;
const token = jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN
});
console.log("The token is: " + token);
const cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
),
httpOnly: true
}
res.cookie('jwt', token, cookieOptions);
req.flash('success', 'You logged in successfully');
res.status(200).redirect("/");
}
})
} catch (error) {
console.log(error);
}
}
exports.register = (req, res) => {
console.log(req.body);
const { username, password, passwordConfirm } = req.body;
db.query('SELECT username FROM users WHERE username = ?', [username], async(error, results) => {
if (error) {
console.log(error);
}
if (results.length > 0) {
req.flash('danger', 'That username is already in use!');
return res.render('register');
} else if (password !== passwordConfirm) {
req.flash('danger', 'Passwords do not match!');
return res.render('register');
}
let hashedPassword = await bcrypt.hash(password, 8);
console.log(hashedPassword);
db.query('INSERT INTO users SET ?', { username: username, password: hashedPassword }, (error, results) => {
if (error) {
console.log(error);
} else {
console.log(results);
req.flash('success', 'User registered!');
return res.render('register');
}
})
});
}
views/register.ejs
<!--Navbar Section-->
<%- include('./partials/header'); %>
<!--End Navbar Section-->
<br>
<% if (messages.danger) { %>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<%- messages.danger %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
<% if (messages.success) { %>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<%- messages.success %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
<div class="container mt-4">
<div class="card">
<div class="card-header">
Register Form
</div>
<div class="card-body">
<form action="/auth/register" method="POST">
<div class="form-group">
<label for="username">Userame: </label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="form-group">
<label for="passwordConfirm">Confirm Password: </label>
<input type="password" class="form-control" id="passwordConfirm" name="passwordConfirm">
</div>
<button type="submit" class="btn btn-primary">Register User</button>
</form>
</div>
</div>
</div>
views/login.ejs
<!--Navbar Section-->
<%- include('./partials/header'); %>
<!--End Navbar Section-->
<br>
<% if (messages.danger) { %>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<%- messages.danger %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% } %>
<div class="container mt-4">
<div class="card">
<div class="card-header">
Login Form
</div>
<div class="card-body">
<form action="/auth/login" method="POST">
<div class="form-group">
<label for="username">Username: </label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
views/partial/header.ejs
<div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<!-- <a class="nav-link" href="#" onclick="document.getElementById('id02').style.display='block'">Sign up</a> -->
<a class="nav-link" href="/register">Register</a>
</li>
<li class="nav-item">
<!-- <a class="nav-link" href="#" onclick="document.getElementById('id01').style.display='block'">Login</a> -->
<a class="nav-link" href="/login">Login</a>
</li>
<li class="nav-item">
<!-- <a class="nav-link" href="#" onclick="document.getElementById('id02').style.display='block'">Sign up</a> -->
<a class="nav-link" href="/logout">Logout</a>
</li>
</ul>
</div>
Use middleware to restrict user to access any page without logging in and
I can't seem to find any reason why logout wont work, if you can give the git repo link then I can help you for sure
problem in code
var userID = req.userid;
var pwd = req.pwd;
console.log("userid = " + userID + "pass = " + pwd);
the console shows values undefined instead of input data
the console shows values undefined instead of input data
I want to take data from an html file and insert into the mongo database using get method. But I am not able to fetch data from the textbox.
Code in nodejs(index.js)
const express = require('express');
const path = require('path');
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const app = express();
app.use(bodyparser());
app.use(bodyparser.urlencoded({
extended: false
}));
app.use(bodyparser.json());
app.set('port', (process.env.PORT || 1000));
mongoose.connect('mongodb://localhost/TrackDB');
var Schema = new mongoose.Schema({
username: String
, pass: String
});
var users = mongoose.model('users', Schema);
app.get("/register", function (req, res) {
var userID = req.userid;
var pwd = req.pwd;
console.log("userid = " + userID + "pass = " + pwd);
new users({
username: userID
, pass: pwd
}).save(function (err, doc) {
if (err) {
res.json(err);
}
else res.send("Successfully Registerd!");
});
console.log("users = " + users);
});
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'));
});
app.listen(1000, () => {
console.log("Server Start......");
});
HTML Page (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LOGIN/REGISTER</title>
<style>
#container {
width: 40%;
margin: auto;
border: 1px solid;
padding: 10px;
padding-left: 200px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="container">
<h1>Register</h1>
<form action="/register">
<div id="register">
<input type="text" name="userid" id="txt_userid" placeholder="Enter user id">
<br>
<input type="password" name="pwd" id="txt_pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_register">Register</button>
</div>
</form>
<h1>Login</h1>
<form action="/login">
<br>
<br>
<div id="login">
<input type="text" name="user" id="userid" placeholder="Enter user id">
<br>
<br>
<input type="password" name="passw" id="pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_login">Login</button>
</div>
</form>
<h1 id="msg"></h1> </div>
</body>
</html>
Try this code
var userID =req.query.userid;
var pwd = req.query.pwd
You need to use POST request, and the data won;t be available in req object. Instead it will be available in req.body
Try:
var userID = req.body.userid;
var pwd = req.body.pwd;
console.log("userid = " + userID + "pass = " + pwd);
You have to use app.post method in node.js.
And use method = post.
<form action="/register" method="post">
<div id="register">
<input type="text" name="userid" id="txt_userid" placeholder="Enter user id">
<br>
<input type="password" name="pwd" id="txt_pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_register">Register</button>
</div>
</form>
Sending data to node uses post, delete, put methods. But if you wish to fetch data back from node you can use .get() method.
I suggest try to print req(i.e console.log(req)). As might be data is stored in req.body.
I have a basic register and login app. After the user registers, and stores their information into my sequelize model, I redirect the page to the login page. When I try to login with the username and password I just made, it doesn't throw any errors, but the page goes into an endless loading phase where it eventually says The localhost page isnt working localhost didn't send any data'ERR_EMPTY_RESPONSE`
//Routes
var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var router = express.Router();
var db = require('../models');
router.get('/', function(req, res){
res.redirect('/friend-book');
});
router.get('/friend-book', function(req, res){
res.render('home');
});
router.get('/friend-book/profile', function(req, res){
res.render('profile');
});
router.get('/friend-book/login', function(req, res){
res.render('login');
});
router.get('/friend-book/register', function(req, res){
res.render('register');
});
router.post('/friend-book/search/user', function(req, res){
db.users.findAll({
where: {
name: req.body.name
}
}).then(function(data){
var userResults = {
people: data
}
res.render('searchedUser', userResults);
})
});
router.post('/friend-book/register', function(req, res){
console.log(req.body);
var name = req.body.name;
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
var description = req.body.description
req.checkBody('name', 'Must type in name.').notEmpty();
req.checkBody('username', 'Must type in Username.').notEmpty();
req.checkBody('email', 'Must type in email.').notEmpty();
req.checkBody('email', 'Invalid Email').isEmail();
req.checkBody('password', 'Must type in password.').notEmpty();
req.checkBody('password2', 'Passwords do not match.').equals(req.body.password);
req.checkBody('description', 'Must type in something about yourself.').notEmpty();
var errors = req.validationErrors();
//If there are errors, render the errors
if(errors){
res.render('register', {
errors: errors
});
}else{
db.users.create(req.body).then(function(data){
console.log("register data", data);
console.log("poop", data.id);
req.session.user = {
id: data.id,
name: data.name,
username: data.username,
email: data.email,
description: data.description
};
req.flash('success_msg', 'Success! Welcome to Book Face!');
// res.render("profile", req.session.user);
res.redirect('/friend-book/login')
});
}
//***************************************************************************************************
});
passport.use(new LocalStrategy(
function(username, password, done) {
db.users.findOne({
where: {
username: username
}
}, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
db.users.findById(id, function(err, user) {
done(err, user);
});
});
router.post('/friend-book/login',
passport.authenticate('local',
{
successRedirect: '/',
failureRedirect: '/friend-book/login',
failureFlash: true
}),function(req, res){
res.redirect('/friend-book/profile' + req.user.username);
}
);
module.exports = router;
//My model
var bcrypt = require('bcryptjs')
module.exports = function(sequelize, DataTypes){
var users = sequelize.define('users', {
name: DataTypes.STRING,
username: DataTypes.STRING,
password: DataTypes.STRING,
email: DataTypes.STRING,
description: DataTypes.STRING
}, {
hooks: {
beforeCreate: function(user, options){
return new Promise(function(resolve, reject){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {reject(err)}
user.password = hash;
console.log(user.password);
resolve();
});
});
})
}
}
});
return users;
}
//login handlebars
<div class="container">
<form action="/friend-book/login" method="POST" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputUsername" class="sr-only">Username</label>
<input type="text" name="username" id="inputUsername" class="form-control" placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
//Registration handlebars
<div class="container">
<h2 class="form-register-heading">Book Face Registration</h2>
{{#if errors}}
{{#each errors}}
<div class="alert alert-warning">{{msg}}</div>
{{/each}}
{{/if}}
<form action="/friend-book/register" method="POST" class="form-signin">
<div class="form-group">
<label for="inputName" class="sr-only">Name</label>
<input type="text" name="name" id="inputName" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label for="inputUsername" class="sr-only">Username</label>
<input type="text" name="username" id="inputUsername" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<label for="inputPassword2" class="sr-only">Password</label>
<input type="password" name="password2" id="inputPassword2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<label for="inputEmail" class="sr-only">Email</label>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label for="inputDescription" class="sr-only">Description</label>
<input type="text" name="description" id="inputDescription" class="form-control" placeholder="Type something">
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>
</div> <!-- /container -->
You only handle POST requests to /friend-book/login.
When you use res.redirect('/friend-book/login'), it'll redirect the user using GET method to that URL.
router.get('/friend-book/login', function (req, res) {
res.render('login');
});