Thursday 18 April 2019

Http Client in Node.js

Making HTTP(S) calls from the application is very common requirement. Node.JS world offers lots of options about how to implement it, or better to say - which package to use.

Native solution


Node.JS comes with native http and https packages.


Request package


It does not support Promises so if we need to wrap it into a Promise ourselves...something like:

/**
 * Function which fetches http response asynchronously.
 * It is implemented as a simple Promise wrapper around request API.
 * @param url Request URL.
 */
function fetchData(url: string): Promise<string> {
    return new Promise((resolve, reject) => {
        if (!url) {
            reject(ErrorFactory.createInvalidArgumentError("url"));
        }

        request(url, (error: any, response: request.Response, body: any) => {
            if (error) {
                reject(error);
            } else {
                if (response) {
                    console.log("statusCode: ", response.statusCode);
                    if (body) {
                        resolve(body);
                    } else {
                        reject(ErrorFactory.createFalsyObjectError("body"));
                    }
                } else {
                    reject(ErrorFactory.createFalsyObjectError("response"));
                }
            }
        });
    });
}


Request package with native promises



node-fetch package


window.fetch API for Node.js 

Axios package


Promise based HTTP client for the browser and node.js

Some References



Conclusion


I've been looking solutions which support Promises. node-fetch seems to be traditional approach and Axios seems to be very popular among developers now.

No comments: