close

[Solved] ReferenceError: fetch is not defined in nodejs

Hello Guys, How are you all? Hope You all Are Fine. Today I am using fetch in my nodejs application and I am facing this error ReferenceError: fetch is not defined in nodejs. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How ReferenceError: fetch is not defined in nodejs Error Occurs ?

I am using fetch in my nodejs application and I am facing this error.

ReferenceError: fetch is not defined

How To Solve ReferenceError: fetch is not defined in nodejs Error ?

  1. How To Solve ReferenceError: fetch is not defined in nodejs Error?

    To Solve ReferenceError: fetch is not defined in nodejs Error Here You need to use an external module for that, like node-fetch. Just Install it in your Node application like this. then put the line below at the top of the files where you are using the fetch API:

  2. ReferenceError: fetch is not defined in nodejs

    To Solve ReferenceError: fetch is not defined in nodejs Error Here You need to use an external module for that, like node-fetch. Just Install it in your Node application like this. then put the line below at the top of the files where you are using the fetch API:

Solution 1: Install node-fetch

Here You need to use an external module for that, like node-fetch. Just Install it in your Node application like this. then put the line below at the top of the files where you are using the fetch API:

npm install node-fetch
const fetch = require("node-fetch");

Now you can use fetch in your nodeJs application.

Solution 2: accessible with a global scope

If it has to be accessible with a global scope

global.fetch = require("node-fetch");

This is a quick dirty fix, please try to eliminate this usage in production code.

Solution 3: Just use cross-fetch

Just use cross-fetch

npm install --save cross-fetch

Usage With promises:

import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';

fetch('//api.github.com/users/lquixada')
  .then(res => {
    if (res.status >= 400) {
      throw new Error("Bad response from server");
    }
    return res.json();
  })
  .then(user => {
    console.log(user);
  })
  .catch(err => {
    console.error(err);
  });

With async/await:

import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';

(async () => {
  try {
    const res = await fetch('//api.github.com/users/lquixada');

    if (res.status >= 400) {
      throw new Error("Bad response from server");
    }

    const user = await res.json();

    console.log(user);
  } catch (err) {
    console.error(err);
  }
})();

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also, Read

Leave a Comment