Making simple HTTP requests in NodeJS

Vishal Raj
2 min readAug 12, 2021

--

Making simple HTTP requests in NodeJS
Photo by Gabriel Heinzer on Unsplash

Of course there are numerous npm packages available to make HTTP requests. Just to name a few, you can use

and many more. These are all super fantastic libraries which bring in an array of capabilities on how to make HTTP request and handle various responses and errors.

But sometimes, all we need is, a simple HTTP/S request and response handler. This can be easily done with NodeJS’s built-in packages http / https with a very simple, lean piece of code. Lets see it in action.

NOTE: Since Promiseis fancy, so I am gonna use it for this.

const { URL } = require('url'),
http = require('http'),
https = require('https');
module.exports = async function request(url, config = {}) {
const u = new URL(url),
secure = 'https:' === u.protocol,
handler = secure ? https : http,
options = {
method: config.method || 'GET',
host: u.hostname,
port: u.port || (secure ? 443 : 80),
path: u.pathname
};
return new Promise(function (resolve, reject) {
const request = handler.request(options, function (response) {
const status = parseInt(response.statusCode, 10);
if ([301, 302, 307].includes(status)) {
resolve(request(request.headers.location, config));
} else if (staus < 200 || https >=400) {
reject(new Error(`Unexpected response, got HTTP ${status}`));
}
const chunks = [];
response.on('data', chunk => chunks.push(chunk));
response.on('end', () => resolve({
status,
data: Buffer.concat(chunks).toString(),
}));
}
request.on('error', reject);
if (request.postBody) {
request.write(postBody);
}
request.end();
});
}

And that will be all.

--

--