HTTP Requests with the Request library in Node.js

Image for post
Image for post

At some point, your web application will need to reach out to a resource for data. In web development, making HTTP requests can be done on the client-side or, in the case of Node, on the server-side. Many cases are made for one over the other, most notably that making requests via the server offers some added security but nevertheless, there are many ways to make those requests within Node. Of those ways, the longstanding and well-established method has been using the “request” library. So we will take a look at how “request” is implemented.

To get started, we will first install the package:

npm install request

Next, following Node’s modules convention, the package is imported into the file that will need to make some HTTP request.

// app.js

With “request” imported, we can begin making HTTP requests. The simplest way to do this is by calling “request” with two arguments. The first argument is the URL as a string, and the second argument is a callback that accepts two arguments. The first argument is the “error” that can potentially be returned from issues with making the request, such as a network failure. The “error” argument can also represent a user error like providing invalid search parameters. The second argument to the callback is the “response” which is returned from the request to the URL. Within the callback’s code block, the different outcomes are handled.

// app.js 

There are many ways to work with the “request” package, but another useful way is by providing as the first argument an object containing certain configurations for the HTTP request. Instead of merely providing the URL, an options object is provided that will configure the request in handling the response. For example:

// app.js

In this slightly modified version, the options object configures the response signaling “request” to parse it, and eliminating the step of manually parsing it. Another benefit of the “request” library is that HTTPS requests, or secured requests, can be made. This is in contrast to Node’s core modules for making HTTP requests which require two separate modules, HTTP and HTTPS.

Aside from Node’s core modules, and the “request” library, there are other libraries that provide HTTP request functionality, some notable ones being Axios, SuperAgent, and Got. For more information on working with “request”, you can read their documentation on Github.

Flatiron School alumni and Full Stack web developer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store