当我在node.js中编译我的代码时,我有这个错误,我该如何修复它?

RefernceError:没有定义fetch

这是我正在做的功能,它负责从特定的电影数据库中恢复信息。

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

当前回答

可能听起来很傻,但我只是简单地调用npm I node-fetch -save在错误的项目。确保您在正确的目录中。

其他回答

你应该在你的文件中添加这个导入:

import * as fetch from 'node-fetch';

然后,运行这段代码来添加节点获取: 添加节点获取

如果你正在使用typescript,那么安装节点获取类型: $ yarn添加@types/node-fetch

你必须使用同构获取模块到你的Node项目,因为Node还不包含获取API。要解决这个问题,请执行以下命令:

npm install --save isomorphic-fetch es6-promise

安装后,在您的项目中使用以下代码:

import "isomorphic-fetch"

Node.js还没有实现fetch()方法,但你可以使用这个出色的JavaScript执行环境的外部模块之一。

在另一个答案中,引用了“节点取回”,这是一个不错的选择。

在你的项目文件夹(你有.js脚本的目录)用命令安装该模块:

npm i node-fetch --save

然后在你想用Node.js执行的脚本中使用它作为一个常量,就像这样:

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

在Node v17的实验标志下——experimental-fetch

它将在不带标志的Node v18中可用。

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

您不再需要安装任何额外的包

你可以使用@lquixada的交叉获取

平台不可知:浏览器,节点或反应本机

安装

npm install --save cross-fetch

使用

承诺:

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

与异步/等待:

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);
  }
})();