Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: fetch is not defined

I have this error when I compile my code in node.js, how can I fix it?

RefernceError: fetch is not defined

enter image description here

This is the function I am doing, it is responsible for recovering information from a specific movie database.

function getMovieTitles(substr){  
  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) {
              var 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);
  });   
}
like image 548
jasa1704 Avatar asked Jan 25 '18 00:01

jasa1704


People also ask

How do you fix ReferenceError fetch is not defined?

The "ReferenceError: fetch is not defined" occurs when the fetch() method is used in an environment where it's not supported - most commonly NodeJs. To solve the error, install and import the node-fetch package, which provides a fetch() compatible API in the NodeJs runtime.

Is fetch available in node?

Fetch is already available as an experimental feature in Node v17. If you're interested in trying it out before the main release, you'll need to first download and upgrade your Node. js version to 17.5.

How define fetch in JavaScript?

JavaScript | fetch() Method. The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.

How do I get fetch data?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.


14 Answers

The fetch API is not implemented in Node.

You need to use an external module for that, like node-fetch.

Install it in your Node application like this

npm install node-fetch 

then put the line below at the top of the files where you are using the fetch API:

import fetch from "node-fetch"; 
like image 73
Adrian Theodorescu Avatar answered Oct 20 '22 12:10

Adrian Theodorescu


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

If fetch has to be accessible with a global scope

import fetch from 'node-fetch'
globalThis.fetch = fetch
like image 23
X.Creates Avatar answered Oct 20 '22 12:10

X.Creates


You can use cross-fetch from @lquixada

Platform agnostic: browsers, node or react native

Install

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);
  }
})();
like image 35
Richard Vergis Avatar answered Oct 20 '22 13:10

Richard Vergis


If you want to avoid npm install and not running in browser, you can also use nodejs https module;

const https = require('https')
const url = "https://jsonmock.hackerrank.com/api/movies";
https.get(url, res => {
  let data = '';
  res.on('data', chunk => {
    data += chunk;
  });
  res.on('end', () => {
    data = JSON.parse(data);
    console.log(data);
  })
}).on('error', err => {
  console.log(err.message);
})
like image 22
Khuram Niaz Avatar answered Oct 20 '22 11:10

Khuram Niaz


Node.js hasn't implemented the fetch() method, but you can use one of the external modules of this fantastic execution environment for JavaScript.

In one of the other answers, "node-fetch" is cited and that's a good choice.

In your project folder (the directory where you have the .js scripts) install that module with the command:

npm i node-fetch --save

Then use it as a constant in the script you want to execute with Node.js, something like this:

const fetch = require("node-fetch");
like image 42
Miguel Murillo Avatar answered Oct 20 '22 12:10

Miguel Murillo


You should add this import in your file:

import * as fetch from 'node-fetch';

And then, run this code to add the node-fetch:
$ yarn add node-fetch

If you're working with typescript, then install node-fetch types:
$ yarn add @types/node-fetch

like image 41
ofir_aghai Avatar answered Oct 20 '22 13:10

ofir_aghai


fetch came to Node v17 under experimental flag --experimental-fetch

It will be available in Node v18 without the flag.

https://github.com/nodejs/node/pull/41749#issue-1118239565

You no longer need any additional package to be installed

like image 25
LearningToCode Avatar answered Oct 20 '22 11:10

LearningToCode


EDITED - New Solution

To use the latest version (3.0.0) you must do the import like this:

const fetch = (url) => import('node-fetch').then(({default: fetch}) => fetch(url));


Old Anwser:

This may not be the best solution, but if you install this version :

npm install [email protected]

you can now use the line below without error's.

const fetch = require("node-fetch");
like image 26
Rafael Lourenço Avatar answered Oct 20 '22 12:10

Rafael Lourenço


You have to use the isomorphic-fetch module to your Node project because Node does not contain Fetch API yet. For fixing this problem run below command:

npm install --save isomorphic-fetch es6-promise

After installation use below code in your project:

import "isomorphic-fetch"
like image 28
AmerllicA Avatar answered Oct 20 '22 12:10

AmerllicA


Best one is Axios library for fetching. use npm i --save axios for installng and use it like fetch, just write axios instead of fetch and then get response in then().

like image 24
Mohammad Quanit Avatar answered Oct 20 '22 13:10

Mohammad Quanit


For those also using typescript on node-js and are getting a ReferenceError: fetch is not defined error

npm install these packages:

    "amazon-cognito-identity-js": "3.0.11"
    "node-fetch": "^2.3.0"

Then include:

import Global = NodeJS.Global;
export interface GlobalWithCognitoFix extends Global {
    fetch: any
}
declare const global: GlobalWithCognitoFix;
global.fetch = require('node-fetch');
like image 20
closedloop Avatar answered Oct 20 '22 13:10

closedloop


It seems fetch support URL scheme with "http" or "https" for CORS request.

Install node fetch library npm install node-fetch, read the file and parse to json.

const fs = require('fs')
const readJson = filename => {
  return new Promise((resolve, reject) => {
    if (filename.toLowerCase().endsWith(".json")) {
      fs.readFile(filename, (err, data) => {
        if (err) {
          reject(err)
          return
        }
        resolve(JSON.parse(data))
      })
    }
    else {
      reject(new Error("Invalid filetype, <*.json> required."))
      return
    }
  })
}

// usage
const filename = "../data.json"
readJson(filename).then(data => console.log(data)).catch(err => console.log(err.message))
like image 44
Expert Ngobeni Avatar answered Oct 20 '22 11:10

Expert Ngobeni


In node.js you can use : node-fetch package

npm i node-fetch

then :

import fetch from 'node-fetch';

here is a full sample in (nodejs) :

import fetch from "node-fetch";

const fetchData = async () => {
  const res = await fetch("https://restcountries.eu/rest/v2/alpha/col"); // fetch() returns a promise, so we need to wait for it

  const country = await res.json(); // res is now only an HTTP response, so we need to call res.json()

  console.log(country); // Columbia's data will be logged to the dev console
};

fetchData();
like image 40
Masoud Ehteshami Avatar answered Oct 20 '22 12:10

Masoud Ehteshami


In HackerRank, some libraries are installed by default and some are not.

Because it is running Node.js, the fetch API is not installed by default.

The best thing for you to do is to check whether the libraries are or not installed.

on the top of the exercise, there is the following:

const https = require('https');

Please try to add this to the top as well:

const axios = require('axios');

and then run the code.

If there is a compilation error, then it's not available, otherwise you can use axios, which is a good alternative to fetch

To use it with then, you can:

function getMovieTitles(substr){
  axios.get(url)
    .then(function(response){
      console.log(response.data);
    })
}

or taking advantage of the async/await

async function getMovieTitles(substr){
  let response = await axios.get(url)
  console.log(response.data);
}
like image 41
nabais Avatar answered Oct 20 '22 13:10

nabais