ReferenceError: fetch is not defined

Cover Image for ReferenceError: fetch is not defined
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

🎉📝🚀 Welcome to my tech blog! Today, we are going to tackle a common issue that many developers encounter: the dreaded ReferenceError: fetch is not defined error in node.js. 😱

So, you've hit a roadblock while compiling your code in node.js and you're wondering how to fix it? Don't worry, I've got you covered! Let's dive in and find a solution to this problem.

The error message points out that the fetch function is not defined. This is because the fetch function is primarily used in the browser, and node.js doesn't have it built-in by default. But fret not, we can easily fix this by using a package called node-fetch. 🎉

To get started, follow these steps:

  1. Open your terminal and navigate to your project directory.

  2. Install node-fetch by running the following command:

    npm install node-fetch
  3. Now, in your code, require node-fetch at the beginning of your file:

    const fetch = require('node-fetch');
  4. That's it! You've successfully fixed the ReferenceError: fetch is not defined issue in node.js. 🎉

Here's an updated version of your code with the necessary changes:

const fetch = require('node-fetch');

function getMovieTitles(substr){  
  let pageNumber=1;
  let url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + pageNumber;
  fetch(url).then((resp) => resp.json()).then(function(data) {
    let movies = data.data;
    let totPages = data.total_pages;
    let sortArray = [];
    for(let i=0; i<movies.length;i++){
        sortArray.push(data.data[i].Title);
     }
    for(let i=2; i<=totPages; i++){
           let newPage = i;
           let url1 = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + newPage;

          fetch(url1).then(function(response) {
              let contentType = response.headers.get("content-type");
              if(contentType && contentType.indexOf("application/json") !== -1) {
                return response.json().then(function(json) {
                  //console.log(json); //uncomment this console.log to see the JSON data.

                 for(let i=0; i<json.data.length;i++){
                    sortArray.push(json.data[i].Title);
                 }

                 if(i==totPages)console.log(sortArray.sort());

                });
              } else {
                console.log("Oops, we haven't got JSON!");
              }
            });

        }
  })
  .catch(function(error) {
    console.log(error);
  });   
}

With these changes, the code will work perfectly in node.js and you won't encounter the ReferenceError: fetch is not defined error anymore.

If you want to learn more about node-fetch and its capabilities, check out the official npm page for this package: node-fetch - npm.

Remember, as a developer, you'll encounter many hurdles along your coding journey, but with the right knowledge and the willingness to learn, you'll overcome them all! 💪

If you found this blog post helpful, please share it with your fellow developers who might be facing the same issue. And don't forget to leave a comment below sharing your thoughts and experiences.

Happy coding! 🚀✨


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello