Understanding the URL Object

HTTP requests from a client include the URL string with the information shown in Figure 7.1. To be able to use the URL information more effectively, Node.js provides the url module, which provides functionality to convert a URL string into a URL object.

To create a URL object from a 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 //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 by using the url.format() method:

url.format(urlObj)

Table 7.1 lists the attributes of the URL objects created by url.parse().

Image

Table 7.1 Properties of the URL object returned by url.parse()

The following is an example of parsing a URL string into an object and then converting it back into a string:

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.43.65