How To Solve The Error “Reference Error Fetch Is Not Defined” In NodeJS?

Referenceerror fetch is not defined in nodejs

While you are working with NodeJS and trying to fetch API from a server to work with, you might get the error “reference error fetch is not defined” in NodeJS. So, why does this happen, and how to solve it? Let’s go into detail.

The cause of this error

This error happens because the fetch method works in an environment that doesn’t support the most commonly NodeJS. If you want to work with ‘fetch’ method, you will have to download ‘node-fetch’ package that provides ‘fetch’ method and then import it into your project.

An example of the error:

import http from "http";
const server = http.createServer(function (req, res) {
  res.end("Hello From the server");
});
 
server.listen(8000, function () {
  console.log("Server is running at 8000");
});
 
fetch("https://dog.ceo/api/breeds/image/random", {
  method: "GET",
})
  .then((res) => res.json())
  .then((json) => {
    console.log(json);
  });

The error:

ReferenceError: fetch is not defined

The solution to the problem “Reference Error Fetch Is Not Defined” in NodeJS

Importing the fetch method through node-fetch is the best way to solve the error “reference error fetch is not defined” in NodeJS.

If you want to install ‘node-fetch’, your project has to have ‘package.json’ file. If you not, you can create one by this command :

npm init

The result :

Now you can install node-fetch with the command:

npm install node-fetch

Or with shortcut:

npm i node-fetch

The result :

Then you can import it and use it in your project.

Example :

import fetch from "node-fetch";
import http from "http";
const server = http.createServer(function (req, res) {
  res.end("Hello From the server");
});
 
server.listen(8000, function () {
  console.log("Server is running at 8000");
});
 
fetch("https://dog.ceo/api/breeds/image/random", {
  method: "GET",
})
  .then((res) => res.json())
  .then((json) => {
    console.log(json);
  });

Output :

Server is running at 8000
{
  message: 'https://images.dog.ceo/breeds/komondor/n02105505_1159.jpg',
  status: 'success'
}

Then you can work with JSON that is server responsive.

This is how you do it in new versions.

Summary

In this tutorial, I explained how to solve the error “Reference error fetch is not defined” in NodeJS. I hope you will enjoy it. If you have any questions about this error, please comment below. Thanks for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *