[go: up one dir, main page]

0% found this document useful (0 votes)
2 views31 pages

HTTP

The document provides a comprehensive guide on implementing HTTP and HTTPS services in Node.js, covering URL processing, request and response handling, and server creation. It details the use of the built-in http and https modules, including the creation of ClientRequest and ServerResponse objects, as well as the steps to set up secure communication using SSL/TLS. Additionally, it discusses the installation of the Express framework and essential middleware for building web applications.
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)
2 views31 pages

HTTP

The document provides a comprehensive guide on implementing HTTP and HTTPS services in Node.js, covering URL processing, request and response handling, and server creation. It details the use of the built-in http and https modules, including the creation of ClientRequest and ServerResponse objects, as well as the steps to set up secure communication using SSL/TLS. Additionally, it discusses the installation of the Express framework and essential middleware for building web applications.
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/ 31

Implementing HTTP Services in

Node.js
• Implementing HTTP Services in Node.js:
Processing URLs,
Understanding Request, Response, and Server Objects,
Implementing HTTP Clients and Servers in Node.js,
Implementing HTTPS Servers and Clients
Processing URLs

• The Uniform Resource Locator (URL) acts as an address label for the
HTTP server to handle requests from the client.
• It provides all the information needed to get the request to the
correct server on a specific port and access the proper data.
• The URL can be broken down into several different components,
each providing a basic piece of information for the webserver on how
to route and handle the HTTP request from the client.
URL Components
• Figure illustrates the basic structure of a URL and the components
that may be included. Not all these components are included in every
HTTP request.
Creation of URL object
• HTTP requests from the client include the URL string with the information
• To create a URL object from the URL string, pass the URL string as the first
• parameter to the following method:
• url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
• The url.parse() method takes the URL string as the first parameter. The
• parseQueryString parameter is a Boolean that when true also parses the
• query string portion of the URL into an object literal. The default is false. The
• slashesDenoteHost is also a Boolean that when true parses a URL with the
• format of //host/path to {host: 'host', pathname: '/path'}
• instead of {pathname: '//host/path'}. The default is false.
• You can also convert a URL object into a string form using the
following url.parse() method. Table lists the attributes of the URL
objects created by url.parse():
• url.format(urlObj)
Resolving the URL Components

• Another useful feature of the url module is the ability to resolve URL
components in the same manner as a browser would. This allows you to
manipulate the URL strings on the server side to make adjustments in the
URL.
• For example, you might want to change the URL location before processing
the request because a resource has moved or changed parameters.
• To resolve a URL to a new location use the following syntax:
• url.resolve(from, to)
• The from parameter specifies the original base URL string. The to parameter
specifies the new location where you want the URL to resolve.
http module
• One of the most important aspects of Node.js is the ability to quickly
implement HTTP and HTTPS servers and services. Node.js provides the
http and https modules
• the http module for is implementing backend web services for your
applications to use. That is where the http module becomes an
invaluable tool in your arsenal.
• You can create basic HTTP servers that provide an interface for
communications behind your firewall and then basic HTTP clients that
interact with those services.
• the http module is pretty low level. It doesn’t provide calls to handle
routing, cookies, caching, and so on. When you get to the
• Express chapters later in this book, you will see the advantages it
provides.
The Built-in HTTP Module
• Node.js has a built-in module called HTTP, which allows Node.js to
transfer data over the Hyper Text Transfer Protocol (HTTP).
Node JS Built-in Objects http
module
1. ClientRequest,
2. ServerResponse,
3. IncomingMessage,
4. and Server objects.
• The most important events, properties, and methods that each
provides also are covered.
The http.ClientRequest Object
• The ClientRequest object is created internally when you call
http.request() when building the HTTP client.
• This object represents the request while it is in progress to the server.
You use the ClientRequest object to initiate, monitor, and handle the
response from the server.
• The ClientRequest implements a Writable stream, so it provides all the
functionality of a Writable stream object. For example, you can use the
write() method to write to it as well as pipe a Readable stream into it.
• To implement a ClientRequest object, you use a call to http.request()
• using the following syntax: http.request(options, callback)
The http.ServerResponse Object
• The ServerResponse object is created by the HTTP server internally
when a request event is received. It is passed to the request event
handler as the second argument. You use the ServerRequest object to
formulate and send a response to the client.
• The ServerResponse implements a Writable stream, so it provides all
the functionality of a Writable stream object. For example, you can
use the write() method to write to it as well as pipe a Readable
stream into it to write data back to the client.
The http.Server Object
• The Node.js HTTP Server object provides the fundamental framework
to implement HTTP servers. It provides an underlying socket that
listens on a port and handles receiving requests and then sends
responses out to client connections.

• The Server object implements EventEmitter and emits the events


• http.createServer([requestListener]) Once you have created the Server object, you can
begin listening on it by calling
• the listen() method on the Server object:
• listen(port, [hostname], [backlog], [callback])
• The first method listen(port, [hostname], [backlog], [callback]) is the one that you will most
likely use. The following list describes
• each of the parameters:
• port: Specifies the port to listen on.
• hostname: Specifies when the hostname will accept connections, and if
• omitted, the server will accept connections directed to any IPv4 address
• (INADDR_ANY).
• backlog: Specifies the maximum number of pending connections that are
• allowed to be queued. This defaults to 511.
• callback: Specifies the callback handler to execute once the server has begun
• listening on the specified port.
Implementing HTTPS Servers
and Clients
• Hypertext Transfer Protocol Secure (HTTPS) is a communications protocol
that provides secure communication between HTTP clients and servers.
• HTTPS is really just HTTP running on top of the SSL/TLS protocol, which is
where it gets its security capabilities.
• HTTP provides security in two main ways.
1. First, it uses longterm public and secret keys to exchange a short-term session
key so that data can be encrypted between client and server.
2. Second, it provides authentication so that you can ensure that the webserver
you are connecting to is the one you actually think it is, thus preventing man-in-
the-middle attacks where requests are rerouted through a third party.
• To implementing HTTP servers and clients in your Node.js
environment using the https module.
• Before getting started using HTTPS, you need to generate a private
key and a public certificate.
• One of the simplest methods is to use the OpenSSL library for your
platform.
• To generate the private key, first execute the following OpenSSL
command:
• openssl genrsa -out server.pem 2048
• Next, use the following command to create a certificate signing
request file:
• openssl req -new -key server.pem -out server.csr
• Then to create a self-signed certificate that you can use for your own
purpose or for testing, use the following command:
• openssl x509 -req -days 365 -in server.csr -signkey server.pem -out
ser
Creating an HTTPS Clients

• Creating an HTTPS client and server is almost exactly like the process of creating an
HTTP client discussed earlier in this chapter.
• The most important options you really need to worry about are key, cert, and agent.
• The key option specifies the private key used for SSL. The cert value specifies the
x509 public key to use. The global agent does not support options needed by HTTPS,
so you need to disable the agent by setting the agent to null, as shown here:
var options = {
key: fs.readFileSync('test/keys/client.pem'),
cert: fs.readFileSync('test/keys/client.crt),
agent: false
};
Creating an HTTPS Server

• Creating an HTTPS server is almost exactly like the process of creating


an HTTP server discussed earlier in this chapter. The only difference is
that there are additional options parameters that you must pass into
• https.createServer(). The options, listed previously in Table, allow you
to specify the security options for the server.
• The most important options you really need to worry about are key
and cert.
• The key option specifies the private key used for SSL. The cert value
specifies the x509 public key to use.
Once the HTTPS server has been created,
the request/response handling works the
same way as for the HTTP servers.
var options = {
key: fs.readFileSync('test/keys/server.pem'),
cert: fs.readFileSync('test/keys/server.crt')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("Hello Secure World\n");
}).listen(8080);
Installing Express
Firstly, install the Express framework globally using NPM so that it can be
used to create a web application using node terminal.
$ npm install express --save
The above command saves the installation locally in
the node_modules directory and creates a directory express inside
node_modules. You should install the following important modules along with
express −
•body-parser − This is a node.js middleware for handling JSON, Raw, Text
and URL encoded form data.
•cookie-parser − Parse Cookie header and populate req.cookies with an
object keyed by the cookie names.
•multer − This is a node.js middleware for handling multipart/form-data.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

You might also like