The http.ClientRequest Object

The ClientRequest object is created internally when you call http.request() when building an HTTP client. This object is intended to represent 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 object 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 the ClientRequest object as well as pipe a Readable stream into it.

To implement a ClientRequest object, you use a call to http.request(), with the following syntax:

http.request(options, callback)

The options parameter is an object whose properties define how to open and send the client HTTP request to the server. Table 7.2 lists the properties that you can specify. The callback parameter is a callback function that is called after a request is sent to the server and that handles the response back from the server. The only parameter to the callback is an IncomingMessage object that is the response from the server.

Image

Table 7.2 Options that can be specified when creating a ClientRequest object

The following code shows the basics of implementation of the ClientRequest object:

var http = require('http'),
var options = {
  hostname: 'www.myserver.com',
  path: '/',
  port: '8080',
  method: 'POST'
};
var req = http.request(options, function(response){
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });
  response.on('end', function () {
    console.log(str);
  });
});
req.end();

ClientRequest objects provide several events that enable you to handle the various states the request may experience. For example, you can add a listener that is called when the response event is triggered by the server’s response. Table 7.3 lists the events available on ClientResponse objects.

Image

Table 7.3 Events available on ClientRequest objects

In addition to providing events, ClientRequest objects also provide several methods that can be used to write data to the request, abort the request, or end the request. Table 7.4 lists the methods available on ClientRequest objects.

Image

Table 7.4 Methods available on ClientRequest objects

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

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