Unit 4
Unit 4
Node.js HTTP
Topics
Basics of Node.js HTTP
Creating simple webs server
Inspecting headers
Request and response
Serving base HTML
Serving a directory
Middleware
Create and use middleware
HTTPs module.
Basics of Node.js HTTP
Following are the modules for creating web applications in
Node.js:
• net: provides the foundation for creating TCP server and client
• dgram: provides functionality for creating UDP/ Datagram sockets
• http: provides a high-performing foundation for an HTTP stack
• https: provides an API for creating TLS/ SSL clients and servers
Node.js HTTP Module
• To make HTTP requests in Node.js, there is a built-in
module HTTP in Node.js to transfer data over the HTTP.
• To use the HTTP server in node, we need to require the HTTP
module.
Syntax:
var http = require('http');
Node.js HTTP Module
• The HTTP module can create an HTTP server that listens to server
ports and gives a response back to the client.
▪ http.request()
Makes an HTTP request to a server, creating an instance of the http.ClientRequest
class.
▪ http.get()
Similar to http.request(), but automatically sets the HTTP method to GET, and calls
req.end() automatically.
Node.js HTTP Module
➢The HTTP module provides 5 classes:
1. http.Agent
2. http.ClientRequest
3. http.Server
4. http.ServerResponse
5. http.IncomingMessage
http.Agent
▪ Node.js creates a global instance of the http.Agent class to manage
connections persistence and reuse for HTTP clients, a key component of
Node.js HTTP networking.
▪ This object makes sure that every request made to a server is queued and a
single socket is reused.
▪ When a response is received, the response event is called with the response,
with an http.IncomingMessage instance as argument.
http.Server
▪ This class is commonly instantiated and returned when creating a new server
using http.createServer().
▪ Once you have a server object, you have access to its methods:
▪ The method you'll always call in the handler is end(), which closes the
response, the message is complete and the server can send it to the client. It
must be called on each response.
http.IncomingMessage
▪ An http.IncomingMessage object is created by:
• http.Server when listening to the request event
• http.ClientRequest when listening to the response event
URL:
http://localhost:8080/?year=2017&month=July
Serving Base HTML
• Create a simple HTML file, that return on every request to GET ‘/’
on the server.
• index.html
<html>
<head>
<title>Hello</title>
</head>
<body>
Full Stack Development
</body>
</html>
Node.js Serving HTML
var fs = require('fs');
var http = require('http');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('index.html', function(err, data){
if(err){
return console.log(err);
}
res.end(data);
});
}).listen(8080);
console.log('Server is running on Port: 8080');
Node.js Stream
• Using streams you read it piece by piece, processing its content without
keeping it all in memory.
Streams basically provide two major advantages over using other data handling
methods:
• Memory efficiency: you don't need to load large amounts of data in memory
before you are able to process it
• Time efficiency: it takes way less time to start processing data, since you can
start processing as soon as you have it, rather than waiting till the whole data
payload is available
Node.js Stream
Different types of streams:
o Readable: a stream you can pipe from, but not pipe into (you can receive
data, but not send data to it). When you push data into a readable stream, it
is buffered, until a consumer starts to read the data.
o Writable: a stream you can pipe into, but not pipe from (you can send data,
but not receive from it)
o Duplex: a stream you can both pipe into and pipe from, basically a
combination of a Readable and Writable stream
}).listen(8080);
console.log('Server is running on Port: 8080');
Instead of waiting until the file is fully read, we start streaming it to the HTTP client as
soon as we have a chunk of data ready to be sent.
Serving a directory
▪ use the path module to resolve the path to the file on the file
system based on the request.url property
▪ see if we have a MIME type registered for the file type requested
▪ make sure the file exists before we try to read it from the file
system
Middleware in Node.js
• Middleware is basically any software that sits between your application code and
some low level API.
• Connect extends the built-in HTTP server functionality and adds a plug-in
framework.
• Calling connect function creates the connect dispatcher. The connect dispatcher is
simply a function that takes the request/response arguments, meaning that the
dispatcher can be used as an argument to http.createServer.
Middleware in Node.js
var connect = require('connect')
http = require('http');
// Create a connect dispatcher
var app = connect();
// Register with http
http.createServer(app).listen(3000);
console.log('server running on port 3000');
• If you run this server, it will return a 404 (Not Found) for every client request.
• This is the built-in behavior provided by connect.
• In the absence of some middleware to handle the client request, connect will return a
404.
Middleware in Node.js
• next allows you to optionally pass the control onto the next middleware
registered with connect OR inform connect about an error
Creating a Connect Middleware
No operation Middleware
//register a middleware
The simplest no-op (no operation) middleware would be one that does not look at the request,
doesn’t modify the response, and doesn’t simply pass over the control to the next middleware.
Creating a Connect Middleware
create Middleware that logs the client request’s method and url.
next();
connect() .use(logit).listen(3000);
Creating a Connect Middleware
➢ create Middleware that echoes the client request back to the
client.
function echo(req, res, next)
req.pipe(res);
connect().use(echo).listen(3000);
Mounting Middleware by Path Prefix
function echo(req, res, next)
{
res.end('Serving echo');
next();
}
var connect = require('connect');
connect()
.use('/echo', echo)
.use(function (req, res) { res.end('Wassup!'); })
.listen(7000);
console.log('server running on port 7000');
Using an Object as Middleware
You have option to use an object to create a middleware as long as the
object has a handle method.
var connect=require('connect');
var echo={
handle: function(req,res,next){
res.end('In Echo');
}
};
connect()
.use(echo)
.listen(3003);
Configurable Middleware
var connect=require('connect');
function greeter(message){
return function(req,res,next){
res.end(message);
}
}
var hello=greeter("Hello World!");
var hey=greeter('Hey There!');
connect()
.use('/hello',hello)
.use('/hey',hey)
.listen(3000);
Chaining Sample: Verifying Requests/Restricting
Access
A simple standardized protocol where every client request needs to contain an
Authorization header.
The header needs to be constructed as follows:
For public-facing web-sites, you will need to get an SSL certificate from a
trusted (one that the user trusts) certification authority (for example, VeriSign
and Thawte). The certificate authority can vouch for the fact that this public key
is uniquely secure to talk to you.