HTTPS requests

If the endpoint is encrypted (for example, a standard HTTPS endpoint), we simply swap out the http module for the https module; the rest of the code remains the same.

In the headers of the opts object, we set Content-Type and Content-Length headers. While the request will still be successful without providing Content-Length , it is good practice and allows the server to make informed assumptions about the payload. However, setting Content-Length to a number lower than the payload size will result in an error. This is why it's important to use Buffer.byteLength , because this gives the exact size of the string in bytes, which can differ from the string length when Unicode beyond the ASCII range are in the string (since Unicode characters can be from one to four bytes, but are treated as a single character where String.prototype.length is concerned).

The http.request method opens a socket that's connected to the endpoint described in the opts  object and returns a stream (which we assign to req).

When we write to this stream (using req.end), data is posted to the endpoint and the underlying socket is closed (because we ended the stream).

Since req is a stream, it also has an error event, which we listen to. This would be fired in the event of network or socket errors, whereas a server error response would be reflected in the response status code.

The fat arrow callback passed to the http.request method is passed a response object, which we named as res. We output the status using res.statusCode. Then we write the Body: label to the process.stdout stream (console.log would add a newline; we don't want that in this case), followed by piping the res object to process.stdout. Finally, we listen to the end event on the res object to add two final newlines to the output (console.log adds an additional newline).

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

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