First and Second input from a form give back 'null' - javascript

So basically I want to create a form that collects user's information and store it in database. Well the problem is that 'fname' and 'name'(the first 2 inputs from the form), for some reason, return 'null' even though they have been filled with text. The problem there is that I cannot add another user due to the fact that there is already a user with the given 'lname' and 'fname' -- in this case 'null'. The strangest part to me is that the other inputs seem to have no problem whatsoever. Any help/suggestion is appreciated.
My user.js Model:
var mongoose = require("mongoose");
var UserSchema = new mongoose.Schema({
firstName: {type: String, unique:true},
lastName: {type: String, unique:true},
email: {type: String, unique: true},
hasVoted: {type: Boolean, default: false}
});
module.exports = mongoose.model("User", UserSchema);
My form:
<!DOCTYPE html>
<html>
<head>
<title>POll</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="/stylesheets/landing.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript" async></script>
</head>
<body>
<div class="row">
<div style="width: 30%; margin: 25px auto;">
<form action="/" method="post">
<div class="form-group">
<input class="form-control" type="text" name="fname" placeholder="First Name">
</div>
<div class="form-group">
<input class="form-control" type="text" name="lname" placeholder="Last Name">
</div>
<div class="form-group">
<input class="form-control" type="text" name="email" placeholder="Email">
</div>
<div class="form-group">
<textarea class="form-control" name="comment">Comment(Optional)</textarea>
</div>
<div class="form-group">
<input type="submit" value="Submit">
</div>
</form>
</div>
</div>
My routes and create mongodb
var express = require("express");
var router = express.Router();
var User = require("../models/user");
router.get("/", function(req, res){
res.render("landing");
});
router.post("/", function(req, res){
// get data from form and add to campgrounds array
var fname = req.body.fname;
var lname = req.body.lname;
var email = req.body.email;
var comment = req.body.comment;
var newUser = {fname: fname, lname: lname, email: email, comment: comment};
// Create a new campground and save to DB
User.create(newUser, function(err, newlyCreated){
if(err){
console.log(err);
} else {
console.log(newlyCreated);
//redirect back to campgrounds page
res.redirect("/", {user: newlyCreated});
}
});
})
module.exports = router;

Shouldn't this:
var newUser = {fname: fname, lname: lname, email: email, comment: comment};
be this:
var newUser = {firstName: fname, lastName: lname, email: email, comment: comment};

Related

Bcrypt compare method returning false

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.

Cannot POST on JS and MongoDB

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.

Sending a POST request using Request module but getting almost empty array of data

I'm trying to send a POST request to an API using the request module but when i console.log the data sent it seems only the time, approved status and id are sent which is by default from the model schema but the rest data are not sent. I need help.
This is what is sent
instead of something like this
console.log(req.body) when i send data with Postman
the request body when i send data with request module
let mongoose = require('mongoose');
//models config
let jobSchema = new mongoose.Schema({
title: String,
category: String,
description: String,
type: String,
url: String,
email: String,
apply: String,
location: String,
company: String,
// path: String,
approved: {type: Boolean, default: false},
created: {type: Date, default: Date.now, expires: 1000}
})
let Job = mongoose.model('Job', jobSchema);
module.exports = Job;
//This is from another file :helpers
exports.createJob = (req, res) => {
db.Job.create(req.body)
.then((newJob) => {
res.status(201).json(newJob)
})
.catch((err) => {
res.send(err)
})
}
//post
app.get('/jobs/add', (req, res) => {
res.render('add')
})
app.post('/jobs', (req, res)=>{
// let formBody = {
// title: req.title,
// category: req.category,
// description: req.body.description,
// type: req.body.type,
// url: req.body.url,
// email: req.bodyemail,
// apply: req.body.apply,
// location: req.body.location,
// company: req.body.company,
// // path: fullPath,
// createdAt: Date.now()
// };
console.log()
request.post({url:'http://localhost:3000/api/jobs/', form: {key:'value'}}, function optionalCallback(err, response, body) {
if (err) {
return console.error('upload failed:', err);
}else{
console.log('Upload successful! Server responded with:', body);
}
return res.redirect('/jobs')
});
})
<div class="add-container">
<form name="myForm" action="/jobs" method="POST" >
<div class="form-group">
<h2>Title(Junior/Graduate/Intern)</h2>
<input type="text" name="job[title]" placeholder="e.g: Junior Front-End Developer" class="form-control" id="title" required="title">
</div>
<div class="form-group">
<h2>Company Name</h2>
<input type="text" name="company" placeholder="e.g: Microsoft" class="form-control" required="company">
</div>
<div class="form-group">
<h2>Job Description</h2>
<textarea id="mytextarea" name="description" placeholder="e.g: We are looking for a Front-End developer with about a year of experience in HTML, CSS, javaScript. Knowledge in React/Vue/Angular is a plus." class="form-control"></textarea>
</div>
<div class="form-group">
<h2>Apply by Website</h2>
<input type="text" name="url" placeholder="e.g: https://wwww.example.com/jobs" class="form-control">
</div>
<div class="form-group">
<h2>How to Apply</h2>
<input type="text" name="apply" placeholder="e.g: send your CV or Resume to..." class="form-control" required="apply">
</div>
<div class="form-group">
<h2>Company Location</h2>
<input type="text" name="location" placeholder="e.g Lagos" class="form-control" required="location">
</div>
<div class="form-group">
<label for="email">Apply by Email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="e.g: job#gmail.com" required="email">
</div>
<!-- <div class="form-group">
<label>Company logo</label>
<input type="file" name="file" single class="form-control" id="file" required="file">
</div> -->
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
remember to start app.js with body-parser urlencoded and json for json data
tested and works
//in app.js
require("dotenv").config(); //to read env variable not needed
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const dbUrl = process.env.DB_URI; //from env variable
const Model = require('./models/model.model');
mongoose
.connect(
dbUrl,
{ useNewUrlParser: true }
)
.then(() => console.log("Connected"))
.catch(error => console.log("Failed " + error));
const app = express();
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
**app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());**
htmlObject = ` <div class="add-container">
<form name="myForm" action="/job" method="POST" >
<div class="form-group">
<h2>Title(Junior/Graduate/Intern)</h2>
<input type="text" name="job[title]" placeholder="e.g: Junior Front-End Developer" class="form-control" id="title" required="title">
</div>
<div class="form-group">
<h2>Company Name</h2>
<input type="text" name="company" placeholder="e.g: Microsoft" class="form-control" required="company">
</div>
<div class="form-group">
<h2>Job Description</h2>
<textarea id="mytextarea" name="description" placeholder="e.g: We are looking for a Front-End developer with about a year of experience in HTML, CSS, javaScript. Knowledge in React/Vue/Angular is a plus." class="form-control"></textarea>
</div>
<div class="form-group">
<h2>Apply by Website</h2>
<input type="text" name="url" placeholder="e.g: https://wwww.example.com/jobs" class="form-control">
</div>
<div class="form-group">
<h2>How to Apply</h2>
<input type="text" name="apply" placeholder="e.g: send your CV or Resume to..." class="form-control" required="apply">
</div>
<div class="form-group">
<h2>Company Location</h2>
<input type="text" name="location" placeholder="e.g Lagos" class="form-control" required="location">
</div>
<div class="form-group">
<label for="email">Apply by Email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="e.g: job#gmail.com" required="email">
</div>
<!-- <div class="form-group">
<label>Company logo</label>
<input type="file" name="file" single class="form-control" id="file" required="file">
</div> -->
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
`;
app.get('/add', (req,res)=>{
res.send(htmlObject);
});
app.post('/job', (req,res)=>{
let model = new Model({
title: req.body.title,
category: req.body.category,
description: req.body.description,
type: req.body.type,
url: req.body.url,
email: req.body.email,
apply: req.body.apply,
location: req.body.location,
company: req.body.company,
path: req.body.path,
createdAt: Date.now().toString()
});
model.save().then(data=>{
res.json({message: 'success', data: data })
});
})
module.exports = app;
//in models/model.js
const mongoose = require("mongoose");
const dataSchema = mongoose.Schema({
title: { type: Number},
category: { type: Number},
description: {type: String},
type: {type: String},
url: {type: String},
email: {type: String},
apply: {type: String},
location: {type: String},
company: {type: String},
path: {type: String},
createdAt: {type: String}
});
module.exports = mongoose.model("data", dataSchema);

i am not able to fetch data from html controls using get method in nodejs and mongodb

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.

Passport JS does not give error but, does not seem to work

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');
});

Categories

Resources