The Request module is one of the most popular Node.js packages for making HTTP requests. It is just a wrapper around Node's native HTTPS module but is much more simple and more user-friendly. When using Request, you can do all of the same things as the native HTTPS module but more easily.

In this article, you will learn how to make HTTP requests using the Request module in a Node.js application. We will be using Reqres fake API for sending different HTTP requests.

Notice: As of February 2020, the Request module is deprecated. It has gone into maintenance mode and stopped considering new features or major releases. You should consider using Axios for making HTTP requests instead. Axios has better defaults and supports promises/async-await.

Installation

Since Request is not a native module, we have to install it as an external dependency. Run the following command in your terminal to install through NPM:

$ npm install request --save

Once you have installed the Request module, you can require it in your code like below:

const request = require('request');

Making Requests

Making an HTTP request is as simple as passing a configuration object or just the URL to the request() method along with a callback function. If an object is provided, it must contain a url property; if no method is specified, GET is used as the default value. Let us look at a simple example:

const request = require('request');

const options = {
    url: 'https://reqres.in/api/users',
    method: 'GET'
};

request(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(JSON.parse(body));
});

The above code simply submits a GET request to our fake API to get a list of users. It parses the returned JSON response and then prints it to the console.

The first parameter to the request() function can either be a URL string or an object literal. Here is a list of important configuration options that you can include in the object:

  • url — The destination URL of the request.
  • method — The HTTP request method like GET or POST.
  • headers — A list of HTTP headers as an object of key-value pairs.
  • json — A shortcut to add Content-type: application/json header. Additionally, parses the response body as JSON.

Shorthand Methods

For convenience, Request also provides shorthand methods for sending different types of HTTP requests. The methods are as follows:

  • request.get() — Defaults to method: "GET
  • request.post() — Defaults to method: "POST"
  • request.put() — Defaults to method: "PUT"
  • request.patch() — Defaults to method: "PATCH"
  • request.del() / request.delete() — Defaults to method: "DELETE"
  • request.head() — Defaults to method: "HEAD"
  • request.options() — Defaults to method: "OPTIONS"

Using the request.get() shorthand method, we can rewrite the above example as follows:

request.get('https://reqres.in/api/users', (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(JSON.parse(body));
});

GET Request

Let us improve the above GET request to set the Content-Type to application/json and get users as a JSON object:

const request = require('request');

request.get('https://reqres.in/api/users', { json: true }, (err, res, body) => {
    if (err) {
        return console.log(err);
    }

    // print the users
    body.data.map(user => {
        console.log(`${user.first_name} ${user.last_name}`);
    });
});

If you want to send query string parameters with a GET request, simply append them to the URL string like below:

request.get('https://www.google.com/search?q=request+module', (err, res, body) => {});

or use qs property in options:

request.get('https://www.google.com/search', {
    qs: {
        q: 'request+module'
    }
}, (err, res, body) => { });

POST Request

Let us use the request.post() method to make an HTTP POST request with JSON data:

const request = require('request');

const options = {
    url: 'https://reqres.in/api/users',
    json: true,
    body: {
        name: 'Atta',
        job: 'Software Engineer'
    }
};

request.post(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(body);
});

POST Request with application/x-www-form-urlencoded

The Request module supports the form requests out-of-the-box. Just use the form property in the options object to set the form data as key-value pairs. The Request module will automatically URL-encode the data and set the Content-Type header to application/x-www-form-urlencoded.

Here is an example:

const request = require('request');

const options = {
    url: 'https://reqres.in/api/login',
    form: {
        email: 'attacomsian',
        password: 'TOP_SECRET'
    }
};

request.post(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(body);
});

PUT and DELETE Requests

The PUT and DELETE requests are very much similar to a POST request. For PUT request, simply use request.put() method instead of using request.post() method.

Here is an example of a DELETE request:

const request = require('request');

request.delete('https://reqres.in/api/users/1', (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log('Status Code:', res.statusCode);
});

Custom HTTP Headers

HTTP Headers, such as User-Agent and Content-Type, can be set in the options object:

const request = require('request');

const options = {
    url: 'https://reqres.in/api/users/1',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'User-Agent': 'Request',
        'X-platform': 'Node'
    }
};

request.get(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(body);
});

HTTP Basic Authentication

The Request module also supports HTTP basic authentication. You can use the auth property in options to specify the login credentials:

const request = require('request');

const options = {
    url: '/login',
    auth: {
        username: 'attacomsian',
        password: 'TOP_SECRET'
    }
};

request.get(options, (err, res, body) => {});

This option will set the HTTP Authorization header to Basic <token>. The token value is calculated by base-64 encoding a string after combing both username and password with a colon.

Request Timeout

By default, if the server does not reply promptly, the client keeps waiting for the response until the request is timed-out. However, using the Request module, we can attach the timeout duration (in milliseconds) manually to the request through the timeout property in options:

const request = require('request');

const options = {
    url: 'http://example.com',
    timeout: 15000
};

request.get(options, (err, res, body) => {});

Conclusion

Request is a powerful HTTP client for making network requests in a Node.js application. If you are looking for a simple yet highly customizable library that can handle HTTP requests effortlessly, the Request module is a good starting point.

However, if you are looking for a modern HTTP client that supports promises & async/await, the Request may not be the right choice. It does not support promises and has a lot of dependencies. If you want the Request to return a promise, you can use an alternative interface wrapper for Request like request-promise-native.

A better and modern alternative would be the Axios library which is a popular HTTP client for making asynchronous HTTP requests in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.