Nodejs fetch API: The Complete Guide

Nodejs fetch API: The Complete Guide

This article was originally published on the DeadSimpleChat blog: Nodejs fetch API: The Complete Guide

Introduction

The fetch API was introduced in the node 18 as available by default.

It provides a method for an easy, logical way to fetch resources asynchronously across the network.

Let's dive deeper into the Node Fetch API

What is Node Fetch API?

The Fetch API provides an interface to connect to the network and fetch resources form the network. If you have use XMLHTTPRequest it is similar to that but new API provides more powerful and cleaner interface and feature set.

The Fetch API used to be available on the client side only but the new node 18 brought the implementation to the server side as well

💡New to DeadSimpleChat? It's a turn key chat that you can easily add to your website or App —without any complicated code. For Virtual / Live events, SaaS App, Social Platform, Education, Gaming, Finance Sign Up for Free

Using the Fetch API

It is very easy to use the node fetch API. First check if you are running the latest version on node js with node -v The fetch API is only available with node 18.

Here is how you can use the fetch API

fetch("https://candystore.com/listofcandies.json")
.then((res)=> res.json())
.then((data)=>console.log(data))
.catch((err)=>{
    console.log("error occured", err)
});

If you want to use the async await key words then

const getCandy = async () => {
    const res = await fetch('https://candystore/listofcandies.json');
    if(res.ok){
        const data = await res.json();
        console.log(data);
    }
}

getCandy();

These were some of the basics of using the fetch API. Next, we will be creating an express / Node application to explain in details the node fetch API.

Here is what we are going to learn

Using Express Js and Node Fetch API

let us create an ExpressJs application.

Let us first check if we are running node 18 or later by typing node -v on our terminal

I am running v18.13.0 . Now install the express js in our application and create a basic route that returns hello world and listens on port 3000

the code for index.js looks like

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Get Requests with Node Fetch API

Let us create a get request using the Node fetch API and get the data from the server and send it to the user.

We will console.log the results to our terminal.

Here is our code:

fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((res)=> res.json())
.then((data)=>console.log(data))
.catch((err)=>{
    console.log("error occured", err)
});

Fetch API using Async Await syntax

const getJsonData = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  if(res.ok){
      const data = await res.json();
      console.log(data);
  }
}

getJsonData();

our index.js code looks like:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((res)=> res.json())
.then((data)=>console.log(data))
.catch((err)=>{
    console.log("error occured", err)
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

and the results that are on our terminal

06:46:29 a@DESKTOP-74KCKLNS node-fetch → node index.js
Example app listening on port 3000
{
  userId: 1,
  id: 1,
  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
  body: 'quia et suscipit\n' +
    'suscipit recusandae consequuntur expedita et cum\n' +
    'reprehenderit molestiae ut ut quas totam\n' +
    'nostrum rerum est autem sunt rem eveniet architecto'
}

What are we doing here:

We are using the fetch API to get data from the jsonplaceholder website then we are logging the data that we receive from the API to the console.

In the next step we will send a POST request using the Node Fetch API

POST Requests using Node Fetch API

In this section, we are going to send a POST request to the jsonplaceholder website with some JSON data

Simple POST request

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: "Hello world",
  headers: {
    'Content-type': 'text/html; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));
//response {id:101}

POST request using the async await syntax:

const getJsonData = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts',{
    method: 'POST',
    body: "Hello World",
    headers: {
      'content-type': 'text/html; charset=UTF-8',
    },
  })
  if(res.ok){
      const data = await res.json();
      console.log(data);
  }
}

getJsonData();

Here we are sending a simple post request with text. Next let us send JSON data using the Node Fetch API

Uploading JSON data using Node Fetch API

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

Using the async await syntax:

const getJsonData = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts',{
    method: 'POST',
    body: JSON.stringify({
      title: 'foo',
      body: 'bar',
      userId: 1,
    }),
    headers: {
      'content-type': 'application/json; charset=UTF-8',
    },
  })
  if(res.ok){
      const data = await res.json();
      console.log(data);
  }
}

Here we are sending JSON data with the fetch request. This is the response that we get from the server

a@DESKTOP-74KChDSFJSDS node-fetch → node index.js
Example app listening on port 3000
{ title: 'foo', body: 'bar', userId: 1, id: 101 }

Next, let us learn how to send a PUT request using the Node Fetch API

PUT Requests using Node Fetch API

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT',
  body: JSON.stringify({
    id: 1,
    title: 'Hello',
    body: 'World',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

getJsonData();
const getJsonData = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1',{
    method: 'PUT',
    body: JSON.stringify({
      title: 'foo',
      body: 'bar',
      userId: 1,
    }),
    headers: {
      'content-type': 'application/json; charset=UTF-8',
    },
  })
  if(res.ok){
      const data = await res.json();
      console.log(data);
  }
}

getJsonData();

Response received from the server:

a@DESKTOP-74KCHFDJS node-fetch → node index.js
Example app listening on port 3000
{ title: 'Hello', body: 'World', userId: 1, id: 1 }

Delete Request using Node Fetch API

Next, we will look into delete request send using the Node Fetch API

fetch('https://jsonplaceholder.typicode.com/posts/1', {
method : 'DELETE',
})

Response received from the server:

{}

Uploading a file

In this section we are going to upload a file using Node Fetch API. Create a text file in the root folder and name it input.txt

Write the below code in the index.js file

const stats = fs.statSync("./input.txt");
const fileSizeInBytes = stats.size;
var bufferContent = fs.readFileSync('./input.txt');

fetch('http://httpbin.org/post', {
    method: 'POST',
    headers: {
        "Content-length": fileSizeInBytes
    },
    body: bufferContent // Here, stringContent or bufferContent would also work
})
.then(function(res) {
    return res.json();
}).then(function(json) {
    console.log(json);
});

here we are uploading to httpbin.org/post and we get the response from the server

{
  args: {},
  data: 'Hello world',
  files: {},
  form: {},
  headers: {
    Accept: '*/*',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': '*',
    'Content-Length': '11',
    Host: 'httpbin.org',
    'Sec-Fetch-Mode': 'cors',
    'User-Agent': 'undici',
    'X-Amzn-Trace-Id': 'Root=1-63c30fb9-23fafcae528f04b23b142bd2'
  },
  json: null,
  origin: '99.234.184.134',
  url: 'http://httpbin.org/post'
}

Using Streams

We are going to be using streams to download the JSON data from using the fetch API.

const getJsonData = async ()=>{

  const response = await fetch('https://httpbin.org/stream/1');

  try {
    for await (const chunk of response.body) {
      const jsonString = Buffer.from(chunk).toString('utf8')
      console.log(JSON.parse(jsonString))
    }
  } catch (err) {
    console.error(err.stack);
  }
}

getJsonData();

Accessing Headers and other Metadata

It is quite easy to access headers and other metadata from Node JS Fetch API

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'GET',
})
  .then((response) => {
    console.log(response.ok);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers.get('content-type'));

  })

response received from the server

a@DESKTOP-74KDSKNS node-fetch → node index.js
Example app listening on port 3000
true
200
OK
application/json; charset=utf-8
undefined

Checking if fetch was successful /Handling exceptions and Errors

We are going to check if the fetch was successful.

fetch("https://jsonplaceholder.typicsdsode.com/posts/1")
.then((res)=> {
  if (!res.ok){
    throw Error("response not ok")
  }
  return res.json()
})
.then((data)=>console.log(data))
.catch((err)=>{
    console.log("error occured", err)
});

Using older versions of Node?node fetch API library

If you have older versions of the node and want to use the Node Fetch API, you can consider using the Node Fetch library. You can easily npm install the library and use it in your app

https://www.npmjs.com/package/node-fetch

Conclusion

In this article I have explained how you can use the node fetch api on the server side, along with examples. I hope this helps you in you quest to use the Fetch API on the server

DeadSimpleChat

DeadSimpleChat as the name implies is a chat application that is easy to use. It has 1-1 Chat and Group Chat along with Chat API and SDK. You explore more about the DeadSimpleChat on its website: https://deadSimpleChat.com