Creating an HTTPS Client

Creating an HTTPS client is almost exactly like creating an HTTP client, discussed earlier in this chapter. The only difference is that there are additional options, shown in Table 7.9, that allow you to specify the security for the client. The most important options are key, cert, and agent.

Image

Table 7.9 Additional options for https.request() and https.createServer()

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 below:

var options = {
  key: fs.readFileSync('test/keys/client.pem'),
  cert: fs.readFileSync('test/keys/client.crt'),
  agent: false
};

You can also create your own custom Agent object, as shown below:

options.agent = new https.Agent(options);

Once you have defined the options with the cert, key, and agent settings, you can call https.request(options, [responseCallback]), and it will work exactly the same as the http.request() call. The only difference is that the data between the client and server is encrypted:

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>
}

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

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