DEV Community

Vishal Raj
Vishal Raj

Posted on • Edited on

2 1

Making simple HTTP requests in NodeJS

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

many more. These all are super fantastic libraries which bring in 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 Promise is fancy, so I am gonna use it for this.

// SimpleHttp.js

const { URL } = require('url'),
    http = require('http'),
    https = require('https');

/**
 * Simple function to make HTTP / HTTPS request.
 *
 * @param {String} url The url to be scraped
 * @param {Object} config The configuration object to make HTTP request
 *
 * @return {Promise}
 */
module.exports = function fetch (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,
            query: config.query || {},
        },
        isHeadRequest = 'HEAD' === options.method;

    return new Promise((resolve, reject) => {
        const request = handler.request(options, function (response) {
            const status = parseInt(response.statusCode, 10);

            if ([301, 302, 307].includes(status)) {
                resolve(load(response.headers.location, options));
            } else if (status < 200 || response >= 400) {
                reject(new Error(`Unexpected response, got HTTP ${status}`));
            } else {
                if (isHeadRequest) {
                    resolve({ headers: response.headersn} );
                } else {
                    const chunks = [];
                    response.on('data', function onData (chunk) {  
                        chunks.push(chunk);
                    });
                    response.on('end', function onEnd () { 
                        resolve({
                            status,
                            body: Buffer.concat(chunks).toString('utf8')
                        });
                    });
                }
            }
        });

        if (options.postBody) {
            request.write(postBody);
        }

        request.on('error', reject);

        request.end();
    });
}
Enter fullscreen mode Exit fullscreen mode

And that will be all.

EDIT: Added support to follow if server responds with HTTP redirect.

💡 One last tip before you go

Tired of spending so much on your side projects? 😒

Just one of many great perks of being part of the network ❤️

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay