Getting error "title not defined " on EJS template engine with Express - javascript

I was learning NodeJS and I am using EJS as templating engine. But whenever I click on register button my Registration page I am getting an error that title is not defined.
Here is my code.
users.js
var express = require('express');
var router = express.Router();
var multer = require('multer');
var uploads = multer({dest: './uploads'});
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register',{
'title': 'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login',{
'title': 'Login'
});
});
router.post('/register', uploads.single('profileImage'), function(req, res, next){
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
//Check for image field
if(req.file){
console.log('Uploading file.....');
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
}
else{
//set a default image
var profileImageName = 'noimage.png';
}
//Form Validation
req.checkBody('name','This field is required').notEmpty();
req.checkBody('email','This field is required').notEmpty();
req.checkBody('email','Invalid Email').isEmail();
req.checkBody('username','This field is required').notEmpty();
req.checkBody('password','This field is required').notEmpty();
req.checkBody('password2','Passwords do not match').equals(req.body.password);
//check for errors
var errors = req.validationErrors();
if(errors){
res.render('register',{
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
}
else{
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileimage: profileImageName
});
//Create user
/*User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});*/
//success message
req.flash('success', 'Your account registered successfully');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
head.ejs
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/bootstrap.css' />
<link rel='stylesheet' href='/stylesheets/style.css' />
header.ejs
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li <% if (title == "Members") { %>class="active" <% } %> >Members</li>
<li <% if (title == "Register") { %>class="active" <% } %> >Register</li>
<li <% if (title == "Login") { %>class="active" <% } %> >Log In</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Log Out</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
register.ejs
<!DOCTYPE html>
<html>
<head>
<% include ./partials/head.ejs %>
</head>
<body>
<div class="container">
<% include ./partials/header.ejs %>
<h1>Register</h1>
<p>Please Register using the below form</p>
<form method="post" action="/users/register" enctype="multipart/form-data">
<div class="form-group">
<label>Name</label>
<input class="form-control" type="text" name="name" placeholder="Enter your name">
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="email" placeholder="Enter your email">
</div>
<div class="form-group">
<label>Username</label>
<input class="form-control" type="text" name="username" placeholder="Enter your username">
</div>
<div class="form-group">
<label>Password</label>
<input class="form-control" type="password" name="password" placeholder="Enter your Password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input class="form-control" type="password" name="password2" placeholder="Confirm your Password">
</div>
<div class="form-group">
<label>Profile Image</label>
<input class="form-control" type="file" name="profileImage">
</div>
<button class="btn btn-default" name="submit" type="submit" value="Register">Register</button>
</form>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="/javascript/bootstrap.js"></script>
</html>
I am not getting why this is happening. I have tried this solution but it's not working. Any help would be appreciated.

I could not understand exactly where your router will redirect when the request hits the /.
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
Usually for / it redirects to index template. Using EJS, you could redirect to a template, for example.
router.get('/', function(req, res, next) {
res.render('index', {param: value});
});
What seems to be happening is that when your request hits the /, it redirects to a template that has head.ejs included, which needs the title parameter sent to it.
In your route to GET, you send this correctly:
router.get('/register', function(req, res, next) {
res.render('register',{
'title': 'Register'
});
});
But, when your request hit the POST method, after all the logic, you don't redirect to a template, you're redirecting it to /, with no parameters. If your / route access a template using your head.ejs, that's why you're getting this error.
In your case, even if your redirecting to index.ejs or to messageUserAdded.ejs (for example), I would then call it with render method to be rendering an EJS template (instead of res.location('/'); and res.redirect('/');), as the following:
res.render('index', {title: 'User Successfully Added'});
And just to add a possibility, you could create a template for successful messages, then you can pass a message to it, customized to each page you have something done right. As an example, a template like this:
successfulMessage.ejs
<html>
<head><title> <%=title%> </title></head>
<body>
<h1>This works!</h1>
<h2> <%=messageTitle%> </h2>
<span> <%=messageDetails%> </span>
</body>
</html>
And then use it in your POST:
// After all the logic
res.render('successfulMessage', {
title: 'Success',
messageTitle: 'Account Created',
messageDetails: 'John has been added to our database!'
})
Hope it helps you to solve it.

I discovered you should NOT name your keys with "reserved" HTML tag names. (list here)
title is a "reserved" HTML tag name thus this will not work properly.

you can change
code
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
to
code
router.get('/', function(req, res, next) {
return res.send('respond with a resource');
});

Related

What is causing the type error in my code?

I am trying to console.log the input in this sign up form but every time i fill the details and the submit the form then it shows the following error
TypeError: Cannot read properties of undefined (reading 'fName')
Kindly let me know the error in my code.
<form action="/" method="POST">
<img class="mb-4" src="images/mail.jpg" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Signup the Newsletter</h1>
<div class="form-floating">
<input type="text" name="fName" class="form-control top" placeholder="First Name">
</div>
<div class="form-floating">
<input type="text" name="lName" class="form-control middle" placeholder="Last Name">
</div>
<div class="form-floating">
<input type="email" name="email" class="form-control bottom" placeholder="name#example.com">
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">Follow me</p>
</form>
// const https = require("https");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(res, req){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
app.listen(3000, function() {
console.log("Server is running on Port 3000");
}); ```
I found these errors in your code, check them and it will work fine.
app.use("/public", express.static(path.join(__dirname, 'public'))); // use this for defining your public folder (and don't forget to import path module above).
app.post("/", function(req, res, next){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
Here as you can see in the callback function we get three parameters first will be the request object, second will be the response object and third is optional next object.
But in your case you are reading it from response object but it should be from request.
Thanks

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.

Login system with nodejs express mysql

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

Why can't I successfully to fetch url from form and thus attribute it to the source(src) of images?

I've having an issue I shouldn't be having with my Node/Express code(s). I can't for the life of me get the image source (src) attribute to work, hence the images added from a form aren't being displayed. It just displays as unknown. I have no idea where I'm going wrong, and have gone through the whole code(s) multiple times, but nothing seems out of place.
The JS code is as follows:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/yelpcamp");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
//Camp Schema
var campgroundSchema = new mongoose.Schema({
name: String,
image: String
});
var Campground = mongoose.model("Campground", campgroundSchema);
app.get("/", function(req, res) {
res.render("landing");
});
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, sites) {
if(err) {
console.log(err);
}
else {
res.render("campgrounds", {
campgrounds:sites
});
}
});
});
app.post("/campgrounds", function(req, res){
//Fetching data from form
var name = req.body.campName;
var url = req.body.imageUrl;
var newCamp = {
name: name,
image: url
};
//New Campground and Save to DB
Campground.create(newCamp, function(err, campground) {
if(err) {
console.log(err);
}
else {
//Redirect to Camp Page
console.log(campground);
res.redirect("/campgrounds");
}
});
});
app.get("/campgrounds/new", function(req, res){
res.render("new");
});
app.listen(4500, function(){
console.log("Yelp Camp Server Started!!!");
});
The following are the relevant EJS codes:
Form EJS
<div class="container">
<form action="/campgrounds" method="POST">
<label for="campName">Name</label>
<input type="text" id="campName" name="campName" placeholder="Add Campground Name">
<label for="campImage">Image</label>
<input type="url" id="campImage" name="imageUrl" placeholder="Add Image Url">
<input type="submit" name="submit" value="Add Campground">
</form>
Go Back
</div>
Add Image EJS
<div class="container">
<h1 style="margin-top: 8%;">Campgrounds Presentation</h1>
<div class="row">
<% campgrounds.forEach(function(campground) { %>
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="thumbnail">
<img src="<%= campground.image %>">
<h3 class=text-center><%= campground.name %></h3>
</div>
</div>
<% }); %>
</div>
</div>

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