Unit2 New
Unit2 New
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])
• 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>
• }