Advantages of Express.js
Makes Node.js web application development fast and easy.
Easy to configure and customize.
Allows you to define routes of your application based on HTTP methods and URLs.
Includes various middleware modules which you can use to perform additional tasks on request and response.
Easy to integrate with different template engines like Jade, Vash, EJS etc.
Allows you to define an error handling middleware.
Easy to serve static files and resources of your application.
Allows you to create REST API server.
Easy to connect with databases such as MongoDB, Redis, MySQL
-------------------------------------------
npm init
It will create package.json file
npm install express --save
As you know, --save will update the package.json file by specifying express.js dependency.
npm install body-parser --save
To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser. This body-parser module parses the JSON, buffer, string and url encoded data submitted using HTTP POST request.
npm install cookie-parser --save
cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
npm install multer --save
multer − This is a node.js middleware for handling multipart/form-data.
npm install mysql
This is a node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.
npm install -g nodemon
npm install --save-dev nodemon
npx nodemon filename.js
This is a tool that automatically restarts a Node application when file changes in a directory are detected.
Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development.
run by calling it from within an npm script (such as npm start) or using npx nodemon.
/******************************************************/
npm install --save cors
npm install cors
Cross-origin resource sharing (CORS) allows AJAX requests to skip the Same-origin policy and access resources from remote hosts.
How to use:
var cors = require('cors')
app.use(cors());
app.use(cors({
origin: 'http://yourapp.com'
}));
app.use(cors({
exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}));
app.use(cors({
credentials: true,
}));
/******************************************************/
npm install express-flash --save
Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
In this node js mysql crud tutorial express flash is used to display a warning, error and information message
npm install express-session --save
Express-session is used to made a session as like in PHP. In this node js mysql crud tutorial, session is needed as the express requirement of express-flash.
npm install express-validator --save
Express validator is used to validate form data it is easy to use. express-validator highly effective and efficient way to accelerate the creation of applications.
npm install method-override --save
NPM is used to run a DELETE and PUT method from an HTML form. In several web browsers only support GET and POST methods.
npm install -g http-server
this will allow you to run a web server from anywhere on your computer.
http-server
Above command will return Urls of hosted files which can be used to check the hosted files on browser.
npm install nodemailer
The Nodemailer module makes it easy to send emails from your computer.
To upgrade, run: npm install npm@latest -g
npm uninstall <package name>
remove a local package from your project.
####################################################################################################################################################################
1. install node.js
2. create directory:
$ mkdir myapp
$ cd myapp
3. Now to create the package.json file using npm, use the following code.
npm init
4. we will further install Express. To install Express and add it to our package.json file, use the following command −
npm install express --save
The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us.
5. we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command
npm install -g nodemon
6. You can now start working on Express.
------------------------------------------
developing our first app using Express:
1. it is time to start developing our first app using Express. Create a new file called index.js and type the following in it.
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send("Hello world!");
});
app.listen(3000);
2. Save the file, go to your terminal and type the following:
nodemon index.js
3. open your browser and go to http://localhost:3000
-----------------------------------------------
Installing database (MySQL)
(https://expressjs.com/en/guide/database-integration.html#mysql)
1. npm install mysql
---------------------------------------------
Installation of template engine only (pug)
$ npm install pug --save
----------------------------------------------
########################################################
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodej...
Installing node + express + jade (pug) template engine
1. npm install express-generator -g
2. First, navigate to where you want to create the project and then run the Express Application
a) express // this command will create default files with .jade template engine
or
a)express node-express-pug-dekho --view=pug // This command will create a project node-express-pug-dekho with .pug template engine
2. change directory:
> cd node-express-pug-dekho
3. install dependencies:
> npm install
4. run the app (Command Prompt (Windows)):
> SET DEBUG=node-express-pug-dekho:* & npm start
run the app (Bash (Linux or macOS))
> DEBUG=node-express-pug-dekho:* npm start
run the app (PowerShell (Windows))
> $ENV:DEBUG = "node-express-pug-dekho:*"; npm start
5. Then load http://localhost:3000/ in your browser to access the app.
Congratulations! You now have a working Express application that can be accessed via port 3000.
6. Enable server restart on file changes
a) npm install --save-dev nodemon //
or
b) npm install -g nodemon // install nodemon globally to your machine, and not only to your project's package.json file:
7. Add below line under script
"scripts": {
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www",
"serverstart": "DEBUG=node-express-pug-dekho:* npm run devstart"
},
8. We can now start the server
a) On Windows, use this command:
SET DEBUG=node-express-pug-dekho:* & npm run devstart
b) On macOS or Linux, use this command
DEBUG=node-express-pug-dekho:* npm run devstart
########################################################
-------------------------------------------
npm install passport passport-local
const passport = require('passport');
---------------------------------------
1. Check version:
node --version
npm --version
2. Express middleware: (http://expressjs.com/en/resources/middleware.html)
body-parser
cors
multer
session
timeout
##########################################################################
1. Create a folder eg nodejs-dekho/
2. create a .js file for fisrt programming in nodejs eg test.js and add below code
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.write(req.url); //Read the Query String
res.end();
}).listen(8080);
3. save and run in cmd
node test.js
4. Open browser and open url
http://localhost:8080/
-------------------------------------------------
How to install package using npm
NPM is a package manager for Node.js packages, or modules if you like.
1. Download a Package
eg Download "upper-case":
C:\Users\Your Name>npm install upper-case
2. NPM creates a folder named "node_modules", where the package will be placed.
My project now has a folder structure like this:
C:\Users\My Name\node_modules\upper-case
3. Once the package is installed, Include the "upper-case" package the same way you include any other module:
var uc = require('upper-case');
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
----------------------------------------------------
install a famous Node.js web framework module called express −
1. npm install express
2. update express:
npm update express
3. Search package:
npm search express
#################################################################
Express.js
################################################################
npm cache clean -f
################################
https://shouts.dev/nodejs-simple-crud-with-expressjs-and-mysql
1. # with NPM command
npm install -g express-generator
2. # create project
express --view=ejs nodejs-crud
# go to the project folder:
cd nodejs-crud
3. npm install
4. npm install mysql --save
5. # to send flash message:
npm install express-flash --save
# to make session like PHP:
npm install express-session --save
# to send PUT and DELETE requests:
npm install method-override --save
# driver to connect Node.js with MySQL:
npm install mysql --save
# development dependency
npm install --save-dev nodemon
npm install --save dotenv // This package loads environmental variables from a .env file into Node’s process.env object.
6. Run and See Output
# run project:
npm start
# project URL:
http://localhost:3000
====================================================
Some useful ejs command:
1. To include a file inside another file we use the following syntax:
<%- include('header.ejs') %>
=============================================================
Definitions:
1. dotenv : This package loads environmental variables from a .env file into Node’s process.env object.
2. bcrypt : is used to hash user passwords or other sensitive information we don’t want to plainly store in our database.
3. body-parser : is used to parse incoming data from request bodies such as form data and attaches the parsed value to an object which can then be accessed by an express middleware.
4. jsonwebtoken : provides a means of representing claims to be transferred between two parties ensuring that the information transferred has not been tampered with by an unauthorized third party, we’ll see exactly how this works later on.
5. mongoose : is an ODM library for MongoDB, provides features such as schema validation, managing relationships between data, etc…
6. express : makes it easy to build API’s and server-side applications with Node, providing useful features such as routing, middlewares, etc..
7. accesscontrol : provides role and attribute-based access control.