0% found this document useful (0 votes)
3 views

expreeupdated

Uploaded by

abhisinghroy21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

expreeupdated

Uploaded by

abhisinghroy21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

EXPRESS.

js TUTORIALS
INTRODUCTION OF EXPRESS.js

Express.js is a web framework for Node.js. It is a


fast, robust and asynchronous in nature. Express is
layer built on the top of the Node.js that helps
manage a server and routes. It provides a robust set
of features to develop web and mobile applications.
Express.js is a routing and Middleware framework for handling
the different routing of the webpage and it works between the
request and response cycle. Middleware gets executed after the
server receives the request and before the controller actions
send the response. Middleware has the access to the request
object, responses object, and next, it can process the request
before the server send a response. An Express-based application
is a series of middleware function calls.
Advantages of using middleware:
•Middleware can process request objects multiple times
before the server works for that request.
•Middleware can be used to add logging and
authentication functionality.
•Middleware improves client-side rendering
performance.
•Middleware is used for setting some specific HTTP
headers.
•Middleware helps for Optimization and better
performance.
EXPRESS.js FEATURES

It can be used to design single-page, multi-page
and hybrid web applications.

It allows to setup middleware's to respond to HTTP
Requests.

It defines a routing table which is used to perform
different actions based on HTTP method and URL.

It allows to dynamically render HTML Pages
based on passing arguments to templates.
Why EXPRESS.js

•Ultra fast I/O


•Asynchronous and single threaded
•MVC like structure
•Robust API makes routing easy
EXPRESS.js sample program

var express = require('express');

var app = express();

app.get('/', function (req, res) {

res.send('Welcome to chandigarh university!');

});

var server = app.listen(8000, function () {

var host = server.address().address;

var port = server.address().port;

console.log('Example app listening at http://%s:%s', host, port);

});

//open webbrowser 127.0.0.1:8000
EXPRESS.js Install

Firstly, you have to install the express framework


globally to create web application using Node
terminal. Use the following command to install
express framework globally.

npm install -g express


npm install express --save
The above command install express in node_module
directory and create a directory named express inside the
node_module. You should install some other important
modules along with express. Following is the list:
•body-parser: This is a node.js middleware for handling
JSON, Raw, Text and URL encoded form data.
•cookie-parser: It is used to 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.
npm install express --save
1.npm install body-parser --save
2.npm install cookie-parser --save
3.npm install multer --save
Express.js App Example
Let's take a simple Express app example which
starts a server and listen on a local port. It only
responds to homepage. For every other path, it will
respond with a 404 Not Found error.
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Welcome to CU');
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:
%s", host, port)
})
express app and send a response to our server with
Middleware
const express = require("express");
const app = express();
const port = process.env.port || 3000;
app.get("/", (req, res, next) => {
console.log("hello");
next();
},
(req, res) => {
res.send(`<div>
<h2>Welcome to CU</h2>
<h5>Chandigarh University</h5>
</div>`);
}
);
app.listen(port, () => {
console.log(`Listening to port ${port}`);
});
express app and send a response to our server without
Middleware
const express = require("express");
const app = express();

const port = process.env.port || 3000;


app.get("/", (req, res) => {
res.send(`<div>
<h2>Welcome to CU</h2>
<h5>Chandigarh University</h5>
</div>`);
});
app.listen(port, () => {
console.log(`Listening to port ${port}`);
});
Express.js
Express.js Request Request
Object Object

Express.js Request objects are the parameters
of the callback function which is used in
Express applications.

The express.js request object represents the
HTTP request and has properties for the
request query string, parameters, body, HTTP
headers, and so on.
Express.js Request
EXPRESS.js REQUEST Object Properties
OBJECT
req.app
PROPERTIES
req.baseurl req.path
req.body req.protocol
req.cookies req.query
req.fresh req.route
req.hostname
req.ip
req.ips
req.originalurl
app.use('/admin', function (req, res, next) { // GET
'http://www.example.com/admin/new?sort=desc'
console.dir(req.originalUrl) // '/admin/new?
sort=desc'
console.dir(req.baseUrl) // '/admin'
console.dir(req.path) // '/new'
next()
})
EXPRESS.js REQUEST
Request Object Methods
METHODS
req.accepts (types)
This method is used to check whether the specified content
types are acceptable, based on the request's Accept HTTP
header field.

Examples:
req.accepts('html');
req.accepts('text/html');
EXPRESS.js REQUEST
Request Object Methods
METHODS
req.is(type)

This method returns true if the incoming request's
"Content-Type" HTTP header field matches the MIME
type specified by the type parameter.

Examples:
req.is('html');
req.is('text/html');
req.is('text/*');
EXPRESS.js REQUEST
Request Object Methods
METHODS
req.param(name [, defaultValue])
This method is used to fetch the value of param
name when present.

EXAMPLE

req.param('name')
EXPRESS.js RESPONSE
Express.js Response Object
OBJECTS

The Response object (res) specifies the HTTP response
which is sent by an Express app when it gets an HTTP
request.

It sends response back to the client browser.

It facilitates you to put new cookies value and that will
write to the client browser (under cross domain rule).

Once you res.send() or res.redirect() or res.render(), you
cannot do it again, otherwise, there will be uncaught error.
EXPRESS.js RESPONSE
PROPERTIES
Response Object Properties

res.app
res.headersSent
res.locals
app.get('/', function (req, res) {
console.dir(res.headersSent) // false
res.send('OK')
console.dir(res.headersSent) // true
})
EXPRESS.js RESPONSE
METHODS Response methods
res.append()
res.attachment()
res.cookie()
res.clearCookie()
res.download()
res.end()
res.format()
res.get()
res.json()
res.links()
res.redirect()
res.render()
res.send()
res.status()
res.type()
EXPRESS.js GET ,POST
REQUEST
GET and POST
GET and POST both are two common HTTP requests used for
building REST(representational state transfer architectural style)
API's. GET requests are used to send only limited amount of data
because data is sent into header while POST requests are used to
send large amount of data because data is sent in the body.
Express.js facilitates you to handle GET and POST requests using
the instance of express.
EXPRESS.js
Index.html POST REQUESTMain.js
<html>
Sample program
var express = require('express');
<body> var app = express();
var bodyParser = require('body-parser');
<form
// Create application/x-www-form-urlencoded parser
action="http://127.0.0.1:8000/process_post" var urlencodedParser = bodyParser.urlencoded({ extended: false })
method="POST"> app.use(express.static('public'));
First Name: <input type="text" app.get('/index.html', function (req, res) {
name="first_name"> <br> res.sendFile( __dirname + "/" + "index.html" );
Last Name: <input type="text" })
app.post('/process_post', urlencodedParser, function (req, res) {
name="last_name"> // Prepare output in JSON format
<input type="submit" value="Submit"> response = {
</form> first_name:req.body.first_name,
</body> last_name:req.body.last_name
</html> };
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
POST
Post method facilitates you to send large amount of data because
data is send in the body. Post method is secure because data is
not visible in URL bar but it is not used as popularly as GET
method. On the other hand GET method is more efficient and
used more than POST.
Let's take an example to demonstrate POST method.
1.<html>
2.<body>
3.<form action="http://127.0.0.1:8000/
process_post" method="POST">
4.First Name: <input type="text" name="first_name"> <br>
5.Last Name: <input type="text" name="last_name">
6.<input type="submit" value="Submit">
7.</form>
8.</body>
9.</html>
1.var express = require('express');
2.var app = express();
3.var bodyParser = require('body-parser');
4.// Create application/x-www-form-urlencoded parser
5.var urlencodedParser = bodyParser.urlencoded({ extended: false })
6.app.use(express.static('public'));
7.app.get('/index.html', function (req, res) {
8. res.sendFile( __dirname + "/" + "index.html" );
9.})
10.app.post('/process_post', urlencodedParser, function (req, res) {
11. // Prepare output in JSON format
12. response = {
13. first_name:req.body.first_name,
14. last_name:req.body.last_name
15. };
16. console.log(response);
17. res.end(JSON.stringify(response));
18.})
19.var server = app.listen(8000, function () {
20. var host = server.address().address
21. var port = server.address().port
22. console.log("Example app listening at http://%s:%s", host, port)
Express.js Routing
Routing is made from the word route. It is used to
determine the specific behavior of an application. It
specifies how an application responds to a client
request to a particular route, URL or path and a
specific HTTP request method (GET, POST, etc.). It
can handle different types of HTTP requests.
1.var express = require('express');
2.var app = express();
3.app.get('/', function (req, res) {
4. console.log("Got a GET request for the homepage");
5. res.send('Welcome to JavaTpoint!');
6.})
7.app.post('/', function (req, res) {
8. console.log("Got a POST request for the homepage");
9. res.send('I am Impossible! ');
10.})
11.app.delete('/del_student', function (req, res) {
12. console.log("Got a DELETE request for /del_student");
13. res.send('I am Deleted!');
14.})
1.app.get('/enrolled_student', function (req, res) {
2. console.log("Got a GET request for /enrolled_student");
3. res.send('I am an enrolled student.');
4.})
5.// This responds a GET request for abcd, abxcd, ab123cd,
and so on
6.app.get('/ab*cd', function(req, res) {
7. console.log("Got a GET request for /ab*cd");
8. res.send('Pattern Matched.');
9.})
10.var server = app.listen(8000, function () {
11.var host = server.address().address
12. var port = server.address().port
13.console.log("Example app listening at http://%s:
%s", host, port)
14.})
EXPRESS.js FILE
Express.js
UPLOAD File Upload and Download
File uploading and downloading are important features of
a web app. Here we are going to handle file upload
using express-fileupload npm package, and the download
is handled using res.download() function of the express.
The express-fileupload is passed to the app as the
middleware.
Approach: First, install express-fileupload module and
then require it and pass it as middleware to the app as
shown below:
const fileUpload = require('express-fileupload')
app.use(fileUpload())
Then in order to access the uploaded files inside POST request
using:
req.files.<uploaded_file_name>
It provides some functions and values such as file name, type,
data, and size. It provides an important mv() function which is
used to save the uploaded file. It takes the upload path and an
error handling function as parameters.

req.files.<uploaded_file_name>.mv(<upload_path>,
function(err) { // statement(s) })
EXPRESS.js
In Express.js,END
file upload is slightly difficult
because of its asynchronous nature and
networking approach.
It can be done by using middleware to
handle multipart/form data. There are
many middleware that can be used like
multer, connect, body-parser etc.
Let's take an example to demonstrate file upload in Node.js.
Here, we are using the middleware 'multer'.
Create a folder "jtp file upload" having the following files:
uploads: It is an empty folder i.e. created to store the
uploaded images.
package: It is JSON file, having the following data:
File: package.json has code
1.{
2. "name": "file_upload",
3. "version": "0.0.1",
4. "dependencies": {
5. "express": "4.13.3",
6. "multer": "1.1.0"
7. },
8. "devDependencies": {
9. "should": "~7.1.0",
10. "mocha": "~2.3.3",
11. "supertest": "~1.1.0"
12. }
13.}
File: index.html
1.<html>
2. <head>
3. <title>File upload in Node.js by CU</title>
4.
5. </head>
6. <body>
7. <h1>Express.js File Upload: by CU</h1>
8. <form id="uploadForm" enctype="multipart/form-data" action="/
uploadCU" method="post">
9. <input type="file" name="myfile" /><br/><br/>
10. <input type="submit" value="Upload Image" name="submit"><br/
><br/>
11. <span id="status"></span>
12. </form>
13. </body>
14.</html>
5.var storage = multer.diskStorage({
6. destination: function (req, file, callback) {
7. callback(null, './uploads');
8. },
9. filename: function (req, file, callback) {
10. callback(null, file.originalname);
11. }
12.});
13.var upload = multer({ storage : storage}).single('myfile');
14.
15.app.get('/',function(req,res){
16. res.sendFile(__dirname + "/index.html");
17.});
18.
19.app.post('/uploadCU',function(req,res){
20. upload(req,res,function(err) {
21. if(err) {
22. return res.end("Error uploading file.");
23. }
24. res.end("File is uploaded successfully!");
25. });
How to Download a File using
Express.js ?
To download a file using express.js we are
going to see two scenarios:
1.Downloading a single file using res.download()
function which takes two parameters the path of the
file and a function to handle if any error occurs.
2.Downloading multiple files as a zipped folder for
this we would use the “express-zip” npm package
which creates a zipped folder using the zip() function
which takes an array of objects as a parameter. Each
object has two fields path and file name.
Steps to Implement File Download in Express
Step 1: Create an “app.js” file and initialize your project with npm.

npm init
Step 2: Now install two npm packages: “express” and “express-
zip“.

npm install express


npm install express-zip
Step 3: Create an “index.html” file and then create a folder named
“Files” inside your project folder. In the files folder creates the
below mentioned four text files:

single_gfg.txt
multiple_one_gfg.txt
multiple_two_gfg.txt
multiple_three_gfg.txt
Step 4: Now let us code the “index.html” file. In it we
will create two forms:
•One with GET route as – ‘/single‘ (to handle the single
file download request).
•One with GET route as – ‘/multiple‘ (to handle the
multiple file download request).
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Download</title>
</head>
<body>
<br>
<!-- Form to handle single file download request-->
<form action="/single" method="get">
<button type="submit">Download Single File</button>
</form>
<br><br>
</body>
</html>
Step 5: Now code the “app.js” file. In it,
we create GET request functions to
handle the download requests using
express. We use “express-zip”
and res.download() as mentioned at the
start.
// filename - app.js
const express = require('express')
const app = express();
const folderPath = __dirname+'/Files';
app.get('/single',function(req,res) {
console.log('single file');
res.download(folderPath+'/single_gfg.txt', function(err) {
if(err) {
console.log(err);
}
})
})

// GET request to the root of the app


app.get('/', function(req, res){
res.sendFile(__dirname+'/index.html');
})
// Creating server at port 3000
app.listen(3000,function(req,res){
console.log('Server started to listen at 3000');
RESTful APIs in Express

RESTful APIs are a popular way of creating web


applications that exchange data over the internet
in a standardized manner. These APIs follow
specific principles such as using resource-based
URLs and HTTP methods to perform various
operations like creating, reading, updating, and
deleting data. ExpressJS is a powerful framework
that allows developers to easily create routes,
handle requests, and send responses, making it a
versatile choice for building APIs that are robust
and scalable.
Understanding the concept of RESTful APIs in
Express JS:
•REST Architecture: REST, which stands for
Representational State Transfer, is an architectural style for
designing networked applications.
•Resource-Based: RESTful APIs in ExpressJS are designed
around resources, which are identified by unique URLs.
These resources represent the entities (e.g., users,
products, articles) that the API manipulates.
•HTTP Methods: RESTful APIs use standard HTTP methods
to perform CRUD (Create, Read, Update, Delete)
operations on resources:
• GET: Retrieves data from a resource.
• POST: Creates a new resource.
• PUT: Updates an existing resource.
• DELETE: Deletes a resource.
•Statelessness: RESTful APIs are stateless, meaning that each request from a
client contains all the information needed to process the request. Servers do not
maintain a session state between requests.
•Uniform Interface: RESTful APIs have a uniform interface, which simplifies
communication between clients and servers. This interface typically involves the
use of standard HTTP methods, resource identifiers (URLs), and representations
(e.g., JSON, XML).
•ExpressJS and Routing: In ExpressJS, you define routes to handle incoming
requests for specific resources and HTTP methods. Each route specifies a
callback function to process the request and send an appropriate response.
•Middleware Integration: ExpressJS middleware can be used to handle tasks
such as request validation, authentication, and response formatting, enhancing
the functionality and security of RESTful APIs.
•Response Codes: RESTful APIs use standard HTTP status codes to indicate the
success or failure of a request. Common status codes include 200 (OK), 201
(Created), 400 (Bad Request), 404 (Not Found), and 500 (Internal Server
Error).
// server.js
const express = require('express');
const app = express();
const PORT = 3000;

// To define the sample data


let books = [
{
id: 1,
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald'
},
{
id: 2,
title: 'To Kill a Mockingbird',
author: 'Harper Lee'
},
];
// Define routes for handling GET requests
app.get('/api/books',
(req, res) => {
res.json(books);
});

app.get('/api/books/:id',
(req, res) => {
const id =
parseInt(req.params.id);
const book =
books.find(book => book.id === id);
if (book) {
res.json(book);
} else {
res.status(404)
.json({ message: 'Book not found' });
}
});
S.No. Git GitHub
1. Git is a software. GitHub is a service.
2. Git is a command-line tool GitHub is a graphical user interface

3. Git is installed locally on the system GitHub is hosted on the web

4. Git is maintained by linux. GitHub is maintained by Microsoft.


Git is focused on version control and GitHub is focused on centralized
5.
code sharing. source code hosting.
Git is a version control system to
GitHub is a hosting service for Git
6. manage source code history.
repositories.

Git was first released in 2005.


7. GitHub was launched in 2008.

Git has no user management


GitHub has a built-in user
8. feature.
management feature.

GitHub includes a free-tier and pay-


9. Git is open-source licensed.
for-use tier.
Git has minimal external tool GitHub has an active marketplace for
10.
configuration. tool integration.
Git provides a Desktop interface GitHub provides a Desktop interface
11.
named Git Gui. named GitHub Desktop.
Git competes with CVS, Azure

You might also like