Node.js built-in HTTP module is used to transfer data over http protocol. It can send HTTP request to external server and get response data.
There are two ways, to send get request from http module. We will see both method one by one.
http.get() method
To use the HTTP module, use require() method to import module.
const http = require('http');
http's get method is used to send get request.
http.get(url, options, callback); // or
http.get(options, callback);
url: required where get request is send. Pass data into query string.
options: optional is object that is sent with request.
callback: function that accept response which is object of http.IncomingMessage
calback object's res.on() 'data'
event receive data into chunk and end method completes request.
const https = require('https');
rawdata = '';
// send request data
https.get('https://jsonplaceholder.typicode.com/todos/1', (res) => {
// append response to variable
res.on('data', (chunk) => {
rawdata += chunk;
});
// print response data
res.on('end', () => {
try {
const parsedData = JSON.parse(rawdata);
console.log(parsedData);
} catch (e) {
connsole.log(e.message);
}
});
}).on('error', (e) => {
console.error(e.message);
});
We receive the string data in response, so we need to convert response to json data using JSON.parse()
method.
http.request() method
http.request(url, options, callback); // or
http.request(options, callback);
url: required where get request is send. You can pass this into options object.
options: optional is object that is sent with request.
callback: function that accept response which is object of http.ClientRequest
In this method, you define request type into options object. In the below example, We have also set url into options object with headers.
const https = require('https');
rawdata = '';
const options = {
hostname: 'jsonplaceholder.typicode.com',
path: '/todos/1',
method: 'get',
headers: {
'Content-Type': 'text/html'
}
}
// send request data
const req = https.request(options, (res) => {
// append response to variable
res.on('data', (chunk) => {
rawdata += chunk;
});
// print response data
res.on('end', () => {
console.log(rawdata);
});
});
req.on('error', (e) => {
console.error(e.message);
});
req.end();
Note that in this method, we should call req.end() to define end of the request. If any error occurs, it will listen on error event.
In this article, we have learned to create http get request and send to the external server. In the next article, we will use post methods of http module.