# How to make HTTP Requests using Node.js Request Module

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 19, 2019, updated Oct 1, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/node-http-requests-using-request-module

> Learn how to use Node.js Request Module to making HTTP requests like GET, POST, PUT, and DELETE.

The [Request module](https://www.npmjs.com/package/request) is one of the most popular Node.js packages for making HTTP requests. It is just a wrapper around Node's native [HTTPS module](https://attacomsian.com/blog/http-requests-in-nodejs) 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](https://reqres.in/) fake API for sending different HTTP requests.

> **Notice:** As of February 2020, the Request module is [deprecated](https://github.com/request/request/issues/3142). It has gone into maintenance mode and stopped considering new features or major releases. You should consider using [Axios](https://attacomsian.com/blog/http-requests-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:

```bash
$ npm install request --save
```

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

```javascript
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:

```javascript
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` &mdash; The destination URL of the request.
* `method` &mdash; The HTTP request method like `GET` or `POST`.
* `headers` &mdash; A list of HTTP headers as an object of key-value pairs.
* `json` &mdash; 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()` &mdash; Defaults to `method: "GET`
* `request.post()` &mdash; Defaults to `method: "POST"`
* `request.put()` &mdash; Defaults to `method: "PUT"`
* `request.patch()` &mdash; Defaults to `method: "PATCH"`
* `request.del()` / `request.delete()` &mdash; Defaults to `method: "DELETE"`
* `request.head()` &mdash; Defaults to `method: "HEAD"`
* `request.options()` &mdash; Defaults to `method: "OPTIONS"`

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

```javascript
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:

```javascript
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:

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

or use `qs` property in options:

```javascript
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:

```java
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:

```java
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:

```javascript
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:

```javascript
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: 

```javascript
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](https://attacomsian.com/blog/nodejs-base64-encode-decode) 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`:

```javascript
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](https://attacomsian.com/blog/promises-javascript) & [async/await](https://attacomsian.com/blog/async-await-javascript), 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](https://github.com/request/request-promise-native).

A better and modern alternative would be the [Axios](https://attacomsian.com/blog/http-requests-axios) library which is a popular HTTP client for making asynchronous HTTP requests in JavaScript.
