[go: up one dir, main page]

0% found this document useful (0 votes)
36 views38 pages

Chapter 9 Express

Uploaded by

Sujeet Kale
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)
36 views38 pages

Chapter 9 Express

Uploaded by

Sujeet Kale
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/ 38

Chapter - 9

Express JS

By Ikhe V. N.
9.1 REST
9.2 Introduction to Express JS
9.3 Routing, Responding
9.4 Configuration
9.5 Views
9.6 Receiving Data
9.7 Error Handling
What is Express?

Express.js provides an easy way to create web server


and render HTML pages for different HTTP requests by
configuring routes for your application.
Express is a minimal and flexible Node.js web application
framework that provides a robust set of features for web and
mobile applications.
It provides us the tools that are required to build our app.
t is flexible as there are numerous modules available on npm,
I

which can be directly plugged into Express.


What is REST API?

1. REST or RESTful stands for REpresentational State Transfer. It is an


architectural style as well as an approach for communications purposes that is
often used in various web services development. In simpler terms, it is an
application program interface (API) that makes use of the HTTP requests to
GET, PUT, POST and DELETE the data over WWW.
2. A web service is a set of open protocols and standards used for exchanging
data between client-server applications. Web services that follow the REST
architecture are known as RESTful web services.
3. REST is web standards based architecture and uses HTTP Protocol. It revolves
around resource where every component is a resource and a resource is
accessed by a common interface using HTTP standard methods.
4. A REST Server simply provides access to resources and REST client accesses
and modifies the resources using HTTP protocol. Here each resource is
identified by URIs/ global IDs. REST uses various representation to represent a
resource like text, JSON, XML but JSON is the most popular one.
HTTP methods

Following four HTTP methods are commonly used in REST based


architecture. The main functions used in any REST-based
architecture are:
● GET − This is used to provide a read only access to a
resource.
● PUT − This is used to create a new resource.
● DELETE − This is used to remove a resource.
● POST − This is used to update a existing resource or create a
new resource.
Principles of REST

there are six ground principles laid down by Dr. Fielding who
was the one to define the REST API design in 2000. Below
are the six guiding principles of REST:
1. Stateless

Requests sent from a client to the server contains all the necessary
information that is required to completely understand it. It can be a
part of the URI, query-string parameters, body, or even headers.
The URI is used for uniquely identifying the resource and the body
holds the state of the requesting resource. Once the processing is
done by the server, an appropriate response is sent back to the
client through headers, status or response body.
Client-Server

1. It has a uniform interface that separates the clients from the servers.
Separating the concerns helps in improving the user interface’s
portability across multiple platforms as well as enhance the scalability
of the server components.
The separation between client and server makes it very easy for the
protocol to be used independently for various development projects.
It allows us to build loosely coupled applications, the client and the
server can evolve Separately.
eg: The client and server may not be concerned about which
software they use.
Uniform Interface

To obtain the uniformity throughout the application, REST has


defined four interface constraints which are:
● Resource identification
● Resource Manipulation using representations
● Self-descriptive messages
● Hypermedia as the engine of application state
Cacheable

In order to provide a better performance, the applications are often


made cacheable. It is done by labeling the response from the
server as cacheable or non-cacheable either implicitly or explicitly. If
the response is defined as cacheable, then the client cache can
reuse the response data for equivalent responses in the future. It
also helps in preventing the reuse of the stale data.
Layered system

The layered system architecture allows an application to be more


stable by limiting component behavior. This architecture enables
load balancing and provides shared caches for promoting
scalability. The layered architecture also helps in enhancing the
application’s security as components in each layer cannot interact
beyond the next immediate layer they are in.
Code on demand

Code on Demand is an optional constraint and is used the least. It


permits a client's code or applets to be downloaded and extended
via the interface to be used within the application. In essence, it
simplifies the clients by creating a smart application which doesn’t
rely on its own code structure.
Practical Demonstration: Building REST API using Node.js

First, you need to create your project directory. Next, open the

command prompt and navigate to your project directory. Once

there, you need to call npm using the below command:


1 npm init
const express = require('express');

const Joi = require('joi'); //used for validation


const app = express();
app.use(express.json());

const books = [
{title: 'Harry Potter', id: 1},
{title: 'Twilight', id: 2},
{title: 'Lorien Legacies', id: 3}
]

//READ Request Handlers


app.get('/', (req, res) => {
res.send('Welcome REST API with Node.js !!');
});

app.get('/api/books', (req,res)=> {
res.send(books);
});
app.get('/api/books/:id', (req, res) => {
const book = books.find(c => c.id ===parseInt(req.params.id));

if (!book) res.status(404).send('<h2 >Ooops... Cant find what you are looking


for!</h2>');
res.send(book);
});

//CREATE Request Handler


app.post('/api/books', (req, res)=> {

const { error } = validateBook(req.body);


if (error){
res.status(400).send(error.details[0].message)
return;
}
const book = {
id: books.length + 1,
title: req.body.title
};
books.push(book);
res.send(book);
});
//UPDATE Request Handler
app.put('/api/books/:id', (req, res) => {
const book = books.find(c=> c.id === parseInt(req.params.id));
if (!book) res.status(404).send('<h2 >Not Found!! </h2>');

const { error } = validateBook(req.body);


if (error){
res.status(400).send(error.details[0].message);
return;
}

book.title = req.body.title;
res.send(book);
});

//DELETE Request Handler


app.delete('/api/books/:id', (req, res) => {

const book = books.find( c=> c.id === parseInt(req.params.id));


if(!book) res.status(404).send('<h2 > Not Found!! </h2>');
const index = books.indexOf(book);
books.splice(index,1);

res.send(book);
});

function validateBook(book) {
const schema = {
title: Joi.string().min(3).required()
};
return Joi.validate(book, schema);

//PORT ENVIRONMENT VARIABLE


const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port $
{port}..`));
to check whether the handlers are working properly or not. For that, we will use a Chrome extension called
Postman. To install Postman you can visit here and click on ‘Add to Chrome’.
testing our GET method
adding a new book to our inventory list. For that, select ‘POST’ from the drop-down list and type in the defined URI
for the POST method. Now, click on ‘Body’, select ‘raw’ and move on to select ‘JSON’ from the drop-down list as
depicted in the below image. Now, in the text area, type in the title of your book
update the book title. Currently, my book title is “Angels and Demons” which I will be updating to “Angels &
Demons”. So, to update the data, you need to first select ‘PUT’ from the drop-down table and enter the PUT
request’s URI along with the book id you wish to update. Next in the ‘Body’, type in the new book title
‘DELETE’ request to delete an existing record. For that select DELETE from the drop-down list and type in the URI
of the delete request handler along with the book details, you want to remove
send a GET request for our final list of books.
Web Server

First of all, import the Express.js module and create the


web server as shown below.

app.js: Express.js Web Server Copy


var express = require('express');
var app = express(); // define routes here..
var server = app.listen(5000, function ()
{ console.log('Node server is running..'); });

Run the above example using node app.js command and point your
browser to http://localhost:5000. It will display Cannot GET / because we
have not configured any routes yet.
1. In the above example, we imported Express.js
module using require() function. The express
module returns a function. This function returns an
object which can be used to configure Express
application (app in the above example).
2. The app object includes methods for routing HTTP
requests, configuring middleware, rendering HTML
views and registering a template engine.
3. The app.listen() function creates the Node.js web
server at the specified host and port. It is identical
to Node's http.Server.listen() method.
Configure Routes

Use app object to define different routes of your


application. The app object includes get(), post(), put()
and delete() methods to define routes for HTTP GET, POST,
PUT and DELETE requests respectively.
We have set up the development, 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);
This will start the server. To test this app, open your browser and go
to http://localhost:3000

The first line imports Express in our file, we have access to it


through the variable Express. We use it to create an application and
assign it to var app.
app.get(route, callback)
This function tells what to do when a get request at the
given route is called. The callback function has 2
parameters, request(req) and response(res). The request
object(req) represents the HTTP request and has properties
for the request query string, parameters, body, HTTP
headers, etc. Similarly, the response object represents the
HTTP response that the Express app sends when it
receives an HTTP request.

res.send()
This function takes an object as input and it sends this to the
requesting client. Here we are sending the string "Hello
World!".
app.listen(port, [host], [backlog], [callback]])
This function binds and listens for connections on the specified host and port.
1) Port :-A port number on which the server should accept incoming requests.
2) Host :- Name of the domain. You need to set it when you deploy your apps to
the cloud.
3) Backlog :- The maximum number of queued pending connections. The default
is 511.
4) Callback :- An asynchronous function that is called when the server starts
listening for requests.
The following example demonstrates configuring routes for HTTP requests.

var express = require('express');


var app = express();
app.get('/', function (req, res)
{ res.send('<html><body><h1>Hello World</h1></body></html>'); });

app.post('/submit-data', function (req, res) { res.send('POST


Request'); });
app.put('/update-data', function (req, res) { res.send('PUT Request'); });

app.delete('/delete-data', function (req, res)


{ res.send('DELETE Request'); });

var server = app.listen(5000, function ()


{ console.log('Node server is running..'); });
In the above example, app.get(), app.post(), app.put()
and app.delete() methods define routes for HTTP GET,
POST, PUT, DELETE respectively. The first parameter is a
path of a route which will start after base URL. The
callback function includes request and response object
which will be executed on each request.
Handle POST Request
you will learn how to handle HTTP POST request and get
data from the submitted form.

First, create Index.html file in the root folder of your


application and write the following HTML code in it.
Body Parser
To handle HTTP POST request in Express.js version 4 and
above, you need to install middleware module called
body-parser. The middleware was a part of Express.js
earlier but now you have to install it separately.

This body-parser module parses the JSON, buffer, string and


url encoded data submitted using HTTP POST request.
Install body-parser using NPM as shown below.
npm install body-parser
var express = require('express');
var app = express();
Var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) { res.sendFile('index.html');
});
app.post('/submit-student-data',
function (req, res) { var name = req.body.firstName + ' ' +
req.body.lastName;

res.send(name + ' Submitted Successfully!'); }); var server =


app.listen(5000, function () { console.log('Node server is
running..'); });
In the above example, POST data can be accessed
using req.body. The req.body is an object that
includes properties for each submitted form.
Index.html contains firstName and lastName input
types, so you can access it using req.body.firstName
and req.body.lastName.
run the above example using node server.js command, point your
browser to http://localhost:5000 and see the following result.

You might also like