当我在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);
  });   
}

当前回答

这个答案并没有直接回答这个问题。相反,它提出了一种替代方案。

为什么?因为使用'node-fetch'变得越来越复杂,因为你不能使用const fetch = require('node-fetch')导入更新的版本。你需要做更多的事情才能让它成功。

尝试使用axios包:

简单安装npm i axios 抓取的代码是这样的

const response = await axios.get(url).then(res => res.data)

其他回答

如果您使用的是18之前的Node版本,那么获取API并不是开箱即用的,您需要使用外部模块来实现,比如节点获取。

像这样在Node应用程序中安装它

npm install node-fetch

然后把下面的一行放在你正在使用fetch API的文件的顶部:

import fetch from "node-fetch";

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

npm install --save isomorphic-fetch es6-promise

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

import "isomorphic-fetch"
npm i node-fetch 

一旦安装,在你的JavaScript文件中:

import fetch from "node-fetch";

最后制作这个更改包。json文件:

"type": "module"

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

import * as fetch from 'node-fetch';

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

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

这个答案并没有直接回答这个问题。相反,它提出了一种替代方案。

为什么?因为使用'node-fetch'变得越来越复杂,因为你不能使用const fetch = require('node-fetch')导入更新的版本。你需要做更多的事情才能让它成功。

尝试使用axios包:

简单安装npm i axios 抓取的代码是这样的

const response = await axios.get(url).then(res => res.data)