DEV Community

alakkadshaw
alakkadshaw

Posted on • Originally published at deadsimplechat.com

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)
});
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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
  • Get Requests with Node Fetch API
  • POST Requests using Node Fetch API
  • Uploading JSON data using Node Fetch API
  • PUT Requests using Node Fetch API
  • Delete Request using Node Fetch API
  • Uploading a file
  • Using Streams
  • Accessing Headers and other Metadata
  • Checking if fetch was successful /Handling exceptions and Errors
  • Using older versions of Node? / Node fetch API library
  • Conclusion

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}`)
})
Enter fullscreen mode Exit fullscreen mode

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)
});
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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}`)
})
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

Response received from the server

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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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',
})
Enter fullscreen mode Exit fullscreen mode

## DELETE request sent 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',
})
Enter fullscreen mode Exit fullscreen mode

DELETE request sent using Node Fetch API

Response received from the server:

{}
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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'));

  })
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
});
Enter fullscreen mode Exit fullscreen mode

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

Image description

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

Top comments (0)