Friday 19 October 2018

Node.js: Make http request

http module provides below methods to make a http request.
http.request(options[, callback])
http.request(url[, options][, callback])

https module provides below methods to make a http request.
https.request(options[, callback])
https.request(url[, options][, callback])

http.request(options[, callback])
http.request(url[, options][, callback])
This method hits the http url and callback function is called with the response from the http url. This method returns an instance of http.ClientRequest. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

Below table summarizes the arguments of ‘http.request’ method.

Argument
Type
Description
url
string or URL
Specifies the http url.
options
Object
Specifies the options supported by request method.

Below table summarizes the options.
Option
Type
Description
protocol
string
Specifies the protocol to use. Default value is http.
host
string
Domain name or ip address of the server to raise the request. Default value is localhost.
hostname
string
Alias for the option host.
family
number
Specify the IP family to use. Valid values are 4 or 6.
port
number
Port of the server. Default value is 80.
localAddress
string
Local interface to bind for network connections
socketPath
string
Unix Domain Socket (use one of host:port or socketPath)
method
string
Specifies the http request method. Default value is GET
path
string
Request path. You can include query parameters also in the path.
headers
Object
Specify request headers.
auth
string
Basic authentication i.e. 'user:password' to compute an Authorization header.
agent
http.Agent or boolean
Controls the agent behavior.

Possible values are:
a.   undefined (default): use http.globalAgent for this host and port.
b.   Agent object: explicitly use the passed in Agent.
c.   false: causes a new Agent with default values to be used.
createConnection
Function
A function that produces a socket/stream to use for the request when the agent option is not used. This can be used to avoid creating a custom Agent class just to override the default createConnection function.
timeout
number
Specifies the socket timeout in milliseconds.
setHost
boolean
Specifies whether or not to automatically add the Host header. Defaults to true.
callback
Function
Callback function is called with response object.

https.request(options[, callback])
https.request(url[, options][, callback])
This methos is used to process https url. Below table summarizes the arguments of this method.
Argument
Type
Description
url
string or URL
Specifies the https url.
options
Object
It accept all the options supported by ‘http.request’ method.  Below are the properties that has different default values compared to ‘http.request’ method.

Option
Default Value
protocol
https
port
443
agent
https.globalAgent
callback
Function
Callback function is called with response object.


Note
a.   You must call request.end() to notify the end of the request
b.   If any error encountered while processing the http request, an error event is emitted from the request object.

Let’s see an example, that hits the url ‘https://self-learning-java-tutorial.blogspot.com/2016/05/java-home-page.html’ and prints the response to the console.

Step 1: Import https module.
var https = require('https');

Step 2: Form the options object.
var options = {
         host : 'self-learning-java-tutorial.blogspot.com',
         port : 443,
         path : '/2016/05/java-home-page.html',
         method : 'GET'
}

Step 3: Hit the url using https.request method.
var request = https.request(options, (response) => {
        
         response.on('data', (content) => {
                  console.log(content);
         })
});

Step 4: End the request.
request.end();

Find the below working application.

HelloWorld.js
var https = require('https');

/* You can ignore specifying port and method, since 443 is the default port number and GET is the default https request.*/
var options = {
 host : 'self-learning-java-tutorial.blogspot.com',
 port : 443,
 path : '/2016/05/java-home-page.html',
 method : 'GET'
}

var request = https.request(options, (response) => {
 
 response.on('data', (content) => {
  console.log(content);
 })
});

request.end();

When you ran above application, you can see below kind of output.

<Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 63 6c 61 73 73 3d 27 76 32 27 20 64 69 72 3d 27 6c 74 72 27 20 78 6d 6c 6e 73 3d 27 ... >
<Buffer 79 70 65 27 2f 3e 0a 3c 6d 65 74 61 20 63 6f 6e 74 65 6e 74 3d 27 62 6c 6f 67 67 65 72 27 20 6e 61 6d 65 3d 27 67 65 6e 65 72 61 74 6f 72 27 2f 3e 0a ... >
<Buffer 74 6f 20 73 74 61 72 74 20 66 6f 72 20 61 20 62 65 67 69 6e 6e 65 72 2e 20 59 6f 75 20 63 61 6e 20 6c 65 61 72 6e 20 4f 4f 50 73 2c 20 74 68 72 2e 2e ... >

Surprised, it is because, if you do not specfy the response encoding format, node.js return response in binary format.

Specify the endocing using ‘setEncoding’ method of response object.
response.setEncoding('UTF-8');

Adding error handler
/* Adding error handler to this request */
request.on('error', (err) => {
         console.log(`Error occured while sending the request: ${err}`);
})

Find the below working application.

HelloWorld.js

var https = require('https');

/* You can ignore specifying port and method, since 443 is the default port number and GET is the default https request.*/
var options = {
    host: 'self-learning-java-tutorial.blogspot.com',
    port: 443,
    path: '/2016/05/java-home-page.html',
    method: 'GET'
}

var request = https.request(options, (response) => {

    /* Specify encoding*/
    response.setEncoding('UTF-8');

    response.on('data', (content) => {
        console.log(content);
    })
 
 response.on('end', () => {
  console.log('Reached end of response');
 })
});

request.end();

/* Adding error handler to this request */
request.on('error', (err) => {
 console.log(`Error occured while sending the request: ${err}`);
})


Previous                                                 Next                                                 Home

No comments:

Post a Comment