Nodejs fetch API: The Complete Guide
NodeJs Fetch API: The complete guide

Nodejs fetch API: The Complete Guide

Dead Simple Chat Team

Dead Simple Chat offers prebuilt Chat that can be added in minutes to any app or website. Can be completely customized and offers powerful JavaScript Chat API and SDK.

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)
});
using the fetch

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();
fetch api using async await

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

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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}`)
})
index.js

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 get data 

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();
using the async await syntax

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}`)
})
index.js

and the results that are on our terminal

06:46:29 a@DESKTOP-74KCUSDS 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'
}
node.js

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

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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}
simple post request

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();
POST request using the Node Fetch API and async await syntax

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

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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));
uploading JSON data using Node Fetch API

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);
  }
}
using the async await syntax

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

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

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

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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();
PUT Request using Node Fetch API
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();
using the async await syntax

Response received from the server:

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

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',
})
DELETE request sent using Node Fetch API

Response received from the server:

{}
response received from the server
Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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);
});
index.js

here we are uploading to httpbin.org/post and we get the respose 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'
}
response from the server
Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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();
Using streams and Node fetch API to get data

Accessing Headers and other Metadata

It is quite easy to access headers and other meta data 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'));

  })
accessing headers and other metadata

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
response received from the server

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)
});
checking for exceptions and errors

Using older versions of Node?node fetch API library

If you have older versions of 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
Node Fetch library

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

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat