Unit IV
Unit IV
INTRODUCTION
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
Example Program 1:
Index.js
var express = require('express');
var app = express();
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;
<!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!”
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
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.