0% found this document useful (0 votes)
31 views36 pages

Unit 4

The document discusses Node.js HTTP modules and creating web servers in Node.js. It covers creating HTTP servers, handling requests and responses, serving static files and directories, using streams, and implementing middleware.

Uploaded by

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

Unit 4

The document discusses Node.js HTTP modules and creating web servers in Node.js. It covers creating HTTP servers, handling requests and responses, serving static files and directories, using streams, and implementing middleware.

Uploaded by

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

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.

• Use the createServer() method to create an HTTP server:


Node.js as a Web Server
var http = require('http’);

//create a server object:


http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
Node.js HTTP Module
Methods:
▪ http.createServer():
Return a new instance of the http.Server class. It takes a callback and returns an
HTTP server. On each client request, the callback is passed in two arguments- the
incoming request stream and an outgoing server response stream. To start the
returned HTTP server, simply call its listen function passing in the port number you
want to listen on.

▪ 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.

▪ It also maintains a pool of sockets. This is key for performance reasons.


http.ClientRequest
▪ An http.ClientRequest object is created when http.request() or http.get() is
called.

▪ 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:

▪ close() stops the server from accepting new connections


▪ listen() starts the HTTP server and listens for connections
http.ServerResponse
▪ Created by an http.Server and passed as the second parameter to the request
event it fires.

const server = http.createServer((req, res) => {


//res is an http.ServerResponse object
//req is an http.IncomingMessage object
})

▪ 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

▪ It can be used to access the response:


• status using its statusCode and statusMessage methods
• headers using its headers method or rawHeaders
• HTTP method using its method method
• HTTP version using the httpVersion method
• URL using the url method
• underlying socket using the socket method
Setting the Status code
• By default, the status code is 200.
• As long as the headers are not sent, you can explicitly set the
status code using the statusCode response member.
• Example:
response.statusCode = 404;
Setting Headers
• Any HTTP header can be set in the response using the
response.setHeader(name, value) member function.
• One common header that you need to set is the Content-Type of the response
so that the client knows how to interect the data the server sends in the body.
response.setHeader("Content-Type", "text/html");
• The formal term for the value of the Content-Type header is MIME type.
MIME types for a few key content types are as follow:
Add an HTTP Header
• If the response from the HTTP server is supposed to be displayed as HTML,
you should include an HTTP header with the correct content type
var http = require('http’);
http.createServer(function (req, res) {
console.log(req.headers);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);
Read the Query String
This object has a property called "url" which holds the part of the
url that comes after the domain name
var http = require('http’);
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
Split the Query String
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt);
}).listen(8080);

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

o Transform: a Transform stream is similar to a Duplex, but the output is a


transform of its input
Node.js Stream
• If the file is big, the operation will take quite a bit of time using readfile().
var fs = require('fs');
var http = require('http');

var s=http.createServer(function(req, res){


res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream('./index.html').pipe(res);

}).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.

• A very popular one is connect (npm install connect), which is a middleware


framework.

• 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

var connect = require('connect');


// Create a connect dispatcher and register with http
var app = connect().listen(3000);
console.log('server running on port 3000');
Creating a Connect Middleware
To register a middleware with connect, call the ‘use’ member method on the
connect dispatcher passing in a function that takes three arguments—a request,
a response, and a next callback:

• request derives from the Node.js HTTP request class

• response derives from the Node.js HTTP response class

• 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

var connect = require('connect');

// Create a connect dispatcher and register with http

var app = connect()

//register a middleware

.use(function (req, res, next) { next(); }) .listen(3000);

console.log('server running on port 3000');

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.

var util = require('util');

function logit(req, res, next) {

util.log(util.format('Request recieved: %s, %s', req.method, req.url));

next();

var connect = require('connect');

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);

var connect = require('connect');

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:

• Username and password are combined into a string:


“username:password”.
• The resulting string literal is then encoded using Base64.
• The authorization method and a space, that is, “Basic” is then put before the
encoded string.

• Additionally, to inform the client that it needs to add an Authorization header,


the server should send a WWW-Authenticate header in the response on
rejecting a client request.
https in Node.js

Generate Private Key: openssl genrsa 1024 > key.pem


Generate Public Key: openssl req -x509 -new -key key.pem > cert.pem

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.

You might also like