Making HTTP Requests using Node-Fetch

With Request module depreciated Node-fetch is one of the top recommended libraries to make HTTP request in node.js . This library brings in the window.fetch method to node.js. So, lets dive in to this library and check how could you replace request with node-fetch in your work environment.

Installing Node-fetch

To install node-fetch using npm issue the command below.

npm install node-fetch --save

We would be using a fake rest api service hosted on https://reqres.in/ to make our HTTP calls. Now this library returns a promise . You do have an option to set the promise library if you are not using the native one but we would be going with the native promise implementation.

A Simple GET Request using node-fetch

const fetch = require('node-fetch');
async function e(){
    let x = await fetch('https://reqres.in/api/users')
    console.log(await x.text())
}
e()

Nothing special we have acquired the node-fetch library created an async function and fetched the data from our fake rest API service we used. Now you see that we have called a function .text() which also returns a promise to log data on the console. The reason being that we receive encoded data and decode it we have to use .text() in case of plain text or HTML or .json() in case of JSON Data.

When Using .text() method we decoded it to plain text

When using .json() method it decoded it to the JSON object.

Passing Headers in The Request

To pass headers you just need to pass an additional options object in the fetch method. So our fetch method looks like

var headers ={
    Authorization : "token"
}
fetch(url,{method:'GET', headers})

Making a POST Request

Now as discussed earlier if you have to pass headers you would need to pass it to the additional options object . Similarly you would pass the data to this options object

async function e() {
    var body = {
        "name": "SAM",
        "age": "21",
        "gender": "Male",
        "email": "sam@sam.com"
    }

    var options = {
        method: 'POST',
        body: JSON.stringify(body),
        headers: { 'Content-Type': 'application/json' },
    }
    let x = await fetch('https://reqres.in/api/users', options)
    console.log(await x.json())
}

Now here we make a post request to the fake rest API service. We define an options object this time out method is POST we define what data we are going to send in the body and give appropriate headers and then we pass these options object to the fetch method along with our endpoints. When we call this function we receive the corresponding response from our fake rest API.

{ name: 'SAM',
  age: '21',
  gender: 'Male',
  email: 'sam@sam.com',
  id: '527',
  createdAt: '2020-06-03T17:59:19.206Z' }

This signifies that our POST was successful as this would be the data returned to us by the API if the POST to the route was successful(It is documented).

Now because this returns a promise and we are going ahead with async/await .It would be better if the function definition is enclosed in try/catch, So, that we could catch any error this function throws at us.

Posting Data with file Stream

const { createReadStream } = require('fs');
async function e() {
    const body = createReadStream('data.txt');
    var options = {
        method: 'POST',
        body,
    }
    let x = await fetch('https://reqres.in/api/users', options)
    console.log(await x.json())
}

We need to read the data from the file first and then pass this stream of data to out options object which we would then pass to our fetch method.

Leave a Reply