Install Express
npm install express
Create Express Server
const express=require('express');
const app= express();
const PORT=2000;
app.listen(PORT, ()=>{
console.log('Server running...')
})
Create route
app.get("/", (req, res)=>{
res.send('Welcome to home page');
})
Request Object
- .hostname() - Return hostname.
- .ip() - Return IP address.
- .method() - Return request method,
- .originalUrl() - Return request URL.
- .params() - Return route parameters.
- .path() - Return path.
- .query() - Return query string variables.
- .route() - Return route configuration.
- .secure() - Check connection is secure or not.
- .xhr() - Check request is xhr or not.
Response Object
- .send() - Sends http response.
- .status() - Set http status.
- .render() - Render a view and send rendered HTML string to the client.
- .redirect() - Redirect one location to another.
- .json() - Send JSON format data.
- .download(file_name, new_name, (err)) - Download files.
Set logger in app
Package: morgan
Install: npm install morgan
Load
const logger= require('morgan')
Use Logger
app.use(logger('dev'))
Fetch static files
app.use(express.static('public'))
Set up view engine
Template: EJS (Embedded Java Script)
Install
npm install ejs
app.set('views', path.join(__dirname, "views"))
app.set("view engine", "ejs")
Parse form submitted data
Package: body-parser
Install
npm install body-parser
const bodyParser=require('body-parser');
app.use(bodyParser.urlencoded({extended: false}))
Template Engine (EJS)
<%= %> | To print variables |
<%- include('file_name') %> | To include EJS file |
<% %> | To use statements and loop |
Node JS & MYSQL
Install
npm install mysql
Load MySQL
let mysql=require('mysql')
Establish connection of NODE JS with MYSQL
let config={
host:'localhost',
user:'username',
password:'password',
database:'database_name'
};
let conn= mysql.createConnection(config);
conn.connect( (error)=>{
if(error) throw error;
let sql="sql query";
conn.query(sql, (error, result)=>{
if(error) throw error;
console.log(result);
})
})
conn.end();
Using a query in NODE JS with MYSQL
let config={
host:'localhost',
user:'username',
password:'password',
database:'database_name'
};
let user_id=1;
let conn= mysql.createConnection(config);
conn.connect( (error)=>{
if(error) throw error;
let sql="SELECT * FROM users WHERE id=?";
conn.query(sql, [user_id], (error, results, fields)=>{
if(error) throw error;
console.log(results);
})
})
conn.end();
Middleware in Express JS
Middleware is a function that has access to request objects and response objects.
Create middleware
let isLogin= function(req, res, next){
console.log('Checking user is loginned or not.');
next();
}
How to use middleware in express app
For all routes.
app.use(isLogin);
For single route
app.get("/user_dashboard", isLogin, (req, res,){
res.send('Home page')
})
File upload using NODE JS middleware MULTER
Package: multer
Install
npm install multer
Load multer package
let multer= require('multer')
initialize multer
let upload= multer({
storage: storage,
fileFilter: filter,
limits: { fileSize: 1024*1024}
}). single('file_input_element_name')
Define storage property
let storage= multer.diskStorage({ destination:function(req, file, cb){ console.log(file); cb(null, 'public/upload') }, filename: function( req, file, cb){ cb(null, Date.now()+"-"+file.originalname) } });
Define filter property
let filter= function(req, file, cb){ if(file.mimetype=="image/jpeg" || file.mimetype=="image/jpg" || file.mimetype=="image/png"){ cb(null, true); } else{ cb(new Error('Invalid file type, only jpeg, jpg, png files are allowed.')); } }
Image upload route
app.post("/upload_image", (req, res)=>{
upload(req, res, (error)=>{
if(error){
return res.status(400).send({message: err.message});
}
res.send("Image uploaded successfully.");
})
});
Express Session
Module
express-session
Install Module
npm install express-session
Load express session module
let session=require('express-session')
Use express session module
app.use( session({
secret:"ctalmora", // will reduce the ability to hijack a session to only guessing the session ID
resave:true, // save back to store
saveUninitialized:true // Forces a session that is "uninitialized" to be saved to the store.
}))
Create and use session
req.session.session_variable_name
Destroy session
req.session.destroy( (error)=>{
if(error) throw error
console.log('all session data destroyed');
}}
Express cookies
Module
cookie-parser
Install Module
npm install cookie-parser
Load cookie-parser
let cookieParser=require('cookie-parser');
Use cookie-parser
app.use(cookieParser())
Create or set cookie
res.cookie(cookie_name, value, {expires: new Date(Date.now()+ 3600000*24*30) }) // where 3600000 is milliseconds
res.cookie(cookie_name, value, {maxAge: new Date(Date.now()+ 3600000*24*30) }) // where 3600000 is milliseconds
Get cookie at client side (Browser)
document.cookie
Get cookie at server side
console.log(req.cookies.cookie_name)
Delete a cookie
res.clearCookie(cookie_name)
Restart Node JS app automatically when you changes on server using Nodemon?
Package
nodemon
Install nodemon
npm install nodemon -g
npm install nodemon --save-dev
Use nodemon
At package.json file
{
"name": "newdata",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start":"nodemon app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.5",
"ejs": "^3.1.6",
"express": "^4.17.1",
"express-session": "^1.17.2"
}
}
Validation in express.js
Package
express-validator
Install Package
npm install express-validator
It is middleware that wrap validator.js and sanitizers.
Import express-validator
const {body, validationResult}=require('express-validator')
How to use
app.post("/login",
body('email').isEmail(),
body('password').isLength({min:8, max:20}),
(req, res)=>{
});
Get errors
let errors=validationResult(req); // will return error object
Check errors is empty or not
.isEmpty()
Error methods
- .array() : Return array of validation errors.
- .mapped(): Return object, where the keys are field name and values are validation errors.
Use custom error messages
.withMessage(custom_message_string)
List of functions of validator
isAlphanumeric(str) | Check string contains only alphabet and digits |
isDate({format:'DD/MM/YYYY'}) | Validate date in given format |
isEmail() | Validate email id |
isEmpty() | Check input value has length zero. |
isIn(values) | Check string is in given values or not |
isLength({min: n, max: m}) | Check string length in given min and max value |
isMobilePhone(['en-IN']) | Check string is phone number for specified country |
isInt() | Check string is integer |
isStrongPassword({minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1, minSymbols: 1 }) | Validate string for strong password |
matches(pattern) | Match string with given pattern |
Sanitizers
escape | Replace <, >, ', " with html entities |
ltrim | Remove whitespace from left side |
rtrim | Remove whitespace from right side |
trim | Remove whitespace from both sides |
Quicky create application skelton using express generator
npx express-generator --view=ejs
where --view=ejs is setting view template ejs
Print property value whether property pass or not from controller to view (ejs)
<% if(typeof message !== 'undefined'){ %>
<%= message %>
<% } %>