// create a new folder and setup Node JS in it using command npm init
// install required node dependencies (express, bcyrptjs, body-parser, nodemon) using command 'npm install express' & same for other modules
Project Architecture - refer Image - and create your Dirs & files inside
put your server file name (here app.js) in the main section - (refer above picture)
as well in scripts put "start":"nodemon" inplace of dev - so that you will have to run command once npm start - each time you will edit app.js file it will be auto refreshed on cmd or terminal -
open your folder in cmd and use npm start after making app.js -
//app.js file -
================== app.js Start =======================================
const express = require('express');
const connection = require('./connection.js');
const bodyParser = require('body-parser');
const { signupValidation } = require('./validation');
const { validationResult } = require('express-validator');
const {hashPassword, comparePassword} = require('./helper.js');
const app = express();
app.use(bodyParser());
app.post("/register",(req,res)=>{
var userDetails = req.body;
userDetails.password = hashPassword(userDetails.password);
connection.query('INSERT INTO register(_id,username,name,email,password,mobile)VALUES(?,?,?,?,?,?)',
[
userDetails._id,
userDetails.username,
userDetails.name,
userDetails.email,
userDetails.password,
userDetails.mobile
]
)
res.status(200).json({success: true,userDetails: { _id: userDetails._id, email: userDetails.email, }});
});
app.post("/login",(req,res)=>{
var userDetails = req.body;
const {email} = userDetails;
let checkUser = connection.query('SELECT * FROM register WHERE email = ?', [email], (err, rows) => {
if (err) {
return console.error('Error executing query', err.stack);
}
//console.log(rows[0].password);
//console.log(userDetails.password)
let isValid = comparePassword(userDetails.password, rows[0].password);
if(isValid)
res.send("Login successfull !")
else
res.send("Wrong Password")
});
})
app.listen(3000);
console.log("express Server Started");
=================== app.js End ======================================
Now for connectivity with MySql database create connection.js file
=======================connection.js Start ================================
var mysql = require('mysql');
var conn = mysql.createConnection({
host: 'localhost', // Replace with your host name
user: 'root', // Replace with your database username
password: '', // Replace with your database password
database: 'userapi' // // Replace with your database Name
});
conn.connect(function(err) {
if (err) throw err;
console.log('mysqlDB is connected successfully !');
});
module.exports = conn;
===================connection.js End====================================
Saving Plain password in database is like sin for developers, so we are going to save password in the hashed form - and after that at the time of login compare plain Password to hashed form password-
===================== helper.js=======================================
const bcrypt = require('bcryptjs');
module.exports.hashPassword = function (password){
const salt = bcrypt.genSaltSync();
return bcrypt.hashSync(password, salt);
}
module.exports.comparePassword = function (raw, hash){
return bcrypt.compareSync(raw, hash)
}
//module.exports {hashPassword, comparePassword } //=> for ES6 Node js Dont use here
=================== helper.js end ====================================
now what you want to get saved by user whether it is name or email or password - we should use validator in which we can specify the requirement for perticular field for example there must be unique email or password length must be 6 minimum
=============== validation.js Start ====================================
const { check } = require('express-validator');
exports.signupValidation = [
check('username', 'Name is requied').not().isEmpty(),
check('name', 'Name is requied').not().isEmpty(),
check('email', 'Please include a valid email').isEmail().normalizeEmail({ gmail_remove_dots: true }),
check('password', 'Password must be 6 or more characters').isLength({ min: 5 }),
check('mobile', 'Mobile is requied').isLength({ min: 10 })
]
==================== validation end ===============================
Now Test These APIs on Postman app
// Testing of register or SignUp API
#nodejs #expressJs #coder , #Programming
Location Detected
Location Detected
Sanawad Coordinates
22.1800° N, 76.0700° E
Comments
Post a Comment