0% found this document useful (0 votes)
18 views9 pages

Unit IV

Express is a minimal and flexible Node.js web application framework that simplifies the development of web and mobile applications. It provides essential features such as routing, middleware, and HTTP utility methods, making it efficient and user-friendly. Express is part of the MEAN stack and supports numerous modules from npm for extended functionality.

Uploaded by

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

Unit IV

Express is a minimal and flexible Node.js web application framework that simplifies the development of web and mobile applications. It provides essential features such as routing, middleware, and HTTP utility methods, making it efficient and user-friendly. Express is part of the MEAN stack and supports numerous modules from npm for extended functionality.

Uploaded by

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

UNIT- IV

INTRODUCTION

 Express provides a minimal interface to build our applications.


 It provides us the tools that are required to build our app.
 It is flexible as there are numerous modules available on npm, which can be directly
plugged into Express.
 Express was developed by TJ Holowaychuk and is maintained by the Node.js foundation
and numerous open source contributors.
 Express is a part of MEAN stack, a full stack JavaScript solution used in building fast,
robust, and maintainable production web applications.
o MongoDB(Database)
o ExpressJS(Web Framework)
o AngularJS(Front-end Framework)
o NodeJS(Application Server)
 Express is a node js web application framework that provides broad features for building
web and mobile applications.
 Express is an open-source that is developed and maintained by the Node.js foundation.
 Express is a user-friendly framework that simplifies the development process of Node
applications.
 Express.js is a fast, flexible and minimalist web framework for Node.js.

Advantages of an express framework:


o Time-efficient
o Fast
o Economical
o Easy to learn
o Asynchronous

Features of the Express.js includes


 HTTP Utility Methods: Express mainly used for handling HTTP methods like GET, POST,
PUT, and DELETE. This makes it easy to define how the application should respond to
different types of HTTP requests.
 Routing: Express provides a simple way to define routes for handling HTTP requests.
Routes are used to map different URLs to specific pieces of code, making it easy to
organize your application’s logic.
 Middleware: Express uses middleware functions to perform tasks during the request-
response cycle. Middleware functions have access to the request, response, and the next
middleware function.
 Allows to dynamically render HTML Pages based on passing arguments to templates.
 Static File Serving: It can also serve static files, such as images, CSS, and JavaScript, with
the help of built-in express.static middleware.
 Security: It includes features and middleware to strengthen the security of your web
applications, such as the helmet middleware to secure your app.
How the App Works?

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. Port is the only
required parameter here.
S.No. Argument & Description

port
1
A port number on which the server should accept incoming requests.

host
2
Name of the domain. You need to set it when you deploy your apps to the cloud.

backlog
3
The maximum number of queued pending connections. The default is 511.

callback
4
An asynchronous function that is called when the server starts listening for requests.

Installing Express

D:\expressApp> npm init


D:\expressApp> npm install express –save

Example Program 1:
Index.js
var express = require('express');
var app = express();

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


res.send('Hello World');
})

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


console.log("Express App running at http://127.0.0.1:5000/");
})
D:\expressApp> node index.js
Express App running at http://127.0.0.1:5000/

Run the above program and visit http://localhost:5000/, the browser shows Hello World
message as below:

Let us use sendFile() method to display a HTML form in the index.html file.
onst express = require('express');
const app = express();
const PORT = 3000;

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


//reading single parameter
console.log(req.param('title'));
console.log(req.originalUrl) // '/admin/new?sort=desc'
console.log(req.baseUrl) // '/admin'
console.log(req.path) // '/new'
console.log(req.protocol)
console.log(req.route)
console.log(req.hostname)
console.log(req.ip)
console.log(req.params.name)
res.end();
});

app.listen(PORT, function (err) {


if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="http://localhost:8080/home" method="get">
NAME:<input type="text" name="username"/>
MAIL ID: <input type="mail" name="mailid"/>
<input type="submit" value="SUBMIT">

</form>
</body>
</html>

App.js
var express= require('express');
var app=express();

app.get('/',function(req,res){
res.sendFile(__dirname+"/"+"index.html");

})
app.get('/home',function(req,res){
res.send('<h1>WELCOME:'+req.query['username']+'</h1><br><h2>MAIL ID:
'+req.query['mailid']+'</h2>');

})
app.listen(8080);
post method:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="http://localhost:8080/home" method="post">
NAME:<input type="text" name="username"/>
MAIL ID: <input type="mail" name="mailid"/>
<input type="submit" value="SUBMIT">

</form>
</body>
</html>

App.js
var express= require('express');
var app=express();
var bodyparser=require('body-parser');
var urlEncodedparser=bodyparser.urlencoded({extended:false});

app.get('/',function(req,res){
res.sendFile(__dirname+"/"+"index.html");

})
app.post('/home',urlEncodedparser,function(req,res){
res.send('<h1>WELCOME:'+req.body.username+'</h1><br><h2>MAIL ID:
'+req.body.mailid+'</h2>');

})
app.listen(8080);
In traditional web applications, a web server will wait for HTTP requests to be sent from the
client. Upon receiving a HTTP request, the server will choose the corresponding route handler
and delegate further action to it for that request. Normally, writing a route handler from scratch
can be a bit burdensome in Node. Fortunately, Express provides methods to specify what
function is called for a particular HTTP verb (GET, POST, PUT, etc.) and URL pattern (Route). An
example of a Express route is demonstrated in the code snippet below. Here, Express is declaring
that all GET requests made to the route, /, will be handled with a function that responds to the
client with “Hello World!”

There are mainly five types of Middleware in Express.js:


 Application-level middleware
 Router-level middleware
 Error-handling middleware
 Built-in middleware
 Third-party middleware

Serving Static Files

Express provides a built-in middleware express.static to serve static files, such as images,
CSS, JavaScript, etc.

You simply need to pass the name of the directory where you keep your static assets, to the
express.static middleware to start serving the files directly. For example, if you keep your
images, CSS, and JavaScript files in a directory named public, you can do this –
Middleware

 A request handler with access to the application's request-response cycle is known as


middleware.
 It's a function that holds the request object, the response object, and the middleware
function.
 Middleware can also send the response to the server before the request.
 The next middleware function is commonly represented as a variable named next.
 Simply middleware is a function that can only be applied using routes.
 We can access and modify request and response data using middleware.

Middleware functions can perform the following tasks:

 Execute any code.


 Make changes to the request and the response objects.
 End the request-response cycle.
 Call the next middleware in the stack.

Different Types of Express.js Middleware

You can use the following types of middleware in an Express.js application:

1. Application-level middleware

It runs for all routes in an application. When a user receives an authentication request
program, the middleware moves toward authentication code logic to approve the
authentication. And use the next () function to call the rest of the route. If authentication fails,
the middleware will show an error and the cycle will not respond to the next route.

2. Router-level middleware

This middleware function works the same way as the application level but can generate or
limit an instance using Express.route() function or router.use() function. It runs for all routes
in a router object only.
3. Built-in middleware

This function helps Express to act as a module. You can utilize the Express.json function to
compute and add payloads and the Express. static function to act as application static assets.

4. Error-handling middleware

This middleware function helps to handle errors in the req-res cycle. It defines the
middleware function in the same way with three arguments.

5. Third-party middleware

The user needs to install the node.js technology and load it to the application level at the
router level to let the third-party middleware function work properly. ExpressJS supports
lots of third-party middleware functions, such as

 The bodyParser function is used to parse the requests with payloads and can be installed
using npm install.
 The cookieParser function parses the cookie header by cookie names and can be mounted
by the npm install function.

The basic Express middleware syntax is

app.get (path, (req, res, next) =>


{}, (req, res) => {})

HTTP method for which the middleware function applies.


Path (route) for which the middleware function applies.
The middleware function.
Callback argument to the middleware function, called "next" by convention.
HTTP response argument to the middleware function, called "res" by convention.

You might also like