0% found this document useful (0 votes)
15 views18 pages

Unit2 New

The document discusses implementing HTTP services using Node.js including processing URLs, query strings, request and response objects, creating servers that listen on ports, and examples of static and dynamic servers and clients.

Uploaded by

abimaya006
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)
15 views18 pages

Unit2 New

The document discusses implementing HTTP services using Node.js including processing URLs, query strings, request and response objects, creating servers that listen on ports, and examples of static and dynamic servers and clients.

Uploaded by

abimaya006
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/ 18

IMPLEMENTING HTTP SERVICES

USING NODE JS
UNIT-2
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.
Processing URLs
To create a URL object from the URL string

url.parse(urlStr, [parseQueryString],
[slashesDenoteHost])
EX:
var url = require('url');
var urlStr =
'http://user:[email protected]:80/resource/path?
query=string#hash
var urlObj = url.parse(urlStr, true, false);urlString =
url.format(urlObj);
Resolving the URL Components
• To resolve a URL to a new location use the
following syntax:
• url.resolve(from, to)
• var url = require('url');
• var originalUrl =
'http://user:[email protected]:80/resource/path?
query=string#hash
• var newResource = '/another/path?querynew';
console.log(url.resolve(originalUrl, newResource));
Processing Query Strings and Form
Parameters
• var qstring = require('querystring');
• var params =
qstring.parse("name=Brad&color=red&color=blue")
;
• The params object created would be: {name: 'Brad',
color: ['red', 'blue']}
• You can also go back the other direction and
convert an object to a query string using the
stringify() function shown here:
querystring.stringify(obj, [sep], [eq])
Understanding Request, Response, and
Server Objects
To implement a ClientRequest object, you use a
call to http.request() using the following
syntax:
• http.request(options, callback)
SERVER RESPONSE OBJECTS
• 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.IncomingMessage Object
• The IncomingMessage implements a Readable
stream, allowing you to read the client request
or server response as a streaming source. This
means that the readable and data events can
be listened to and used to read data from the
stream
CREATING A SERVER
• 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])

• 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).
LISTEN()
• 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.
OTHER TWO METHODS
• listen(path, [callback]) –PATH TO A FILE

• Listen((handle, [callback])-OPEN FILE


Implementing HTTP Clients and Servers in
Node.js
STATIC SERVER.JS
var fs = require('fs');
var http = require('http');
var url = require('url');
var ROOT_DIR = "html/";
http.createServer(function (req, res) {
var urlObj = url.parse(req.url, true, false);
fs.readFile(ROOT_DIR + urlObj.pathname, function (err,data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
}).listen(8080)
STATIC CLIENT.JS
var http = require('http');
var options = {
hostname: 'localhost',
port: '8080',
path: '/hello.html‘
};
function handleResponse(response) {
var serverData = '';
response.on('data', function (chunk) {
serverData += chunk;
});
response.on('end', function () {
console.log(serverData);
});
}
http.request(options, function(response){
handleResponse(response);
}).end
DYNAMIC GET SERVER
DYNAMICSERVER.JS
var http = require('http');
var messages = [
'Hello World',
'From a basic Node.js server',
'Take Luck'];
http.createServer(function (req, res) {
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.write('<html><head><title>Simple HTTP Server</title></head>');
res.write('<body>');
for (var idx in messages){
res.write('\n<h1>' + messages[idx] + '</h1>');
}
res.end('\n</body></html>');
}).listen(8080);
DYNAMIC CLIENT.JS
• var options = {
• hostname: 'localhost',
• port: '8080',
• };
• function handleResponse(response) {
• var serverData = '';
• response.on('data', function (chunk) {
• serverData += chunk;
• });
• response.on('end', function() {
• console.log("Response Status:", response.statusCode);
• console.log("Response Headers:", response.headers);
• console.log(serverData);
• });
• }
• http.request(options, function(response){
• handleResponse(response);
• }).end
Interacting with External Sources

• http://openweathermap.org/
• You must go to http://openweathermap.org/
to create an account and get an API key
Implementing HTTPS Servers and Clients
• var options = {
• hostname: 'encrypted.mysite.com',
• port: 443,
• path: '/',
• method: 'GET',
• key: fs.readFileSync('test/keys/client.pem'),
• cert: fs.readFileSync('test/keys/client.crt),
• agent: false
• };
• var req = https.request(options, function(res)) {
• <handle the response the same as an http.request>
• }

You might also like