What is Express js?
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application.
Why use Express JS?
File Name :
Express JS is used to creation of APIs and web applicationsa and mobile applications.
It saves a lot of coding time.
The reason behind creating an express framework for node js is:
Time-efficient
very Fast
Asynchronous
A ExpressJs is used for frontend and backend development.
Express is fast to link it with databases like MySQL, MongoDB, etc.
Express allows dynamic rendering of HTML Pages based on passing arguments to templates.
How to install Express Js?
File Name :
C:\mynode> npm install express
########## OR ###########
C:\mynode> npm install express --save
The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules.
You should install the following important modules along with express −
body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
multer − This is a node.js middleware for handling multipart/form-data.
File Name :
C:\mynode> npm install body-parser --save
C:\mynode> npm install cookie-parser --save
C:\mynode> npm install multer --save
To started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware.
Example
File Name : myapp.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello ittutorial');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("listening at http://%s:%s", host, port)
})
run :- node myapp.js
Request & Response
ExpressJs application uses a callback function that contain Two parameters. which are request and response objects.
File Name :
app.get('/', function (req, res) {
// code here
})
req is object of requrest and res is the object of response.
Request
The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
Request Object Properties
File Name :
req.app
req.baseUrl
req.body
req.cookies
req.fresh
req.hostname
req.ip
req.ips
req.originalUrl
req.params
req.path
req.protocol
req.query
req.route
req.secure
req.signedCookies
req.stale
req.subdomains
Request Object Methods
File Name :
req.accepts(types)
req.get(field)
req.is(type)
req.param(name [, defaultValue])
Response Object :-
The response object represents the HTTP response that an Express app sends when it gets an HTTP request
Response Object Properties
File Name :
res.app
res.headersSent
res.locals
Response Object Methods
File Name :
res.append(field [, value])
res.attachment([filename])
res.cookie(name, value [, options])
res.clearCookie(name [, options])
res.download(path [, filename] [, fn])
res.end([data] [, encoding])
res.status(404).end();
res.format(object)
res.get(field)
res.get('Content-Type');
res.json([body])
res.links(links)
res.location(path)
res.redirect([status,] path)
res.render(view [, locals] [, callback])
res.send([body])
res.sendFile(path [, options] [, fn])
res.sendStatus(statusCode)
res.set(field [, value])
res.status(code)
res.type(type)
Routing
We have seen a basic application which serves HTTP request for the homepage. Routing refers to determining how an application
responds to a client request to a particular endpoint,
which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
File Name :
var express = require('express');
var app = express();
// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Serving Static Files
Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc.
create the name of the directory where you keep your static assets.
the express.static middleware to start serving the files directly.
File Name :
app.use(express.static('public'));
app.use(express.static('public/images'));
app.use(express.static('public/js'));
app.use(express.static('public/css'));
// here public is the directory name.
Example
File Name : myapp.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello Sana Mahtab');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("listening at http://%s:%s", host, port)
})
GET Method
File Name : index.htm
<html>
<body>
<form action = "http://127.0.0.1:8081/users_get" method = "GET">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
File Name : myapp.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.get('/users_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("listening at http://%s:%s", host, port)
})
POST Method
File Name : index.htm
<html>
<body>
<form action = "http://127.0.0.1:8081/users_post" method = "POST">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
File Name : myapp.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/users_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("listening at http://%s:%s", host, port)
})
File Upload
File Name : index.htm
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "http://127.0.0.1:8081/file_upload" method = "POST"
enctype = "multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
File Name : myapp.js
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ) {
console.log( err );
} else {
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Cookies Management
File Name :
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8081)
Previous
Next