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

当前回答

这招对我很管用:

const nodeFetch = require('node-fetch') as typeof fetch;

其他回答

这是一个快速修复,请尝试在生产代码中消除这种用法。

如果fetch必须在全局范围内访问

import fetch from 'node-fetch'
globalThis.fetch = fetch

对我来说,这些看起来更简单。

npm install node-fetch
import fetch from "node-fetch";

编辑-新的解决方案

要使用最新版本(3.0.0),必须像这样导入:

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


古老的回答:

这可能不是最好的解决方案,但如果你安装这个版本:

npm install node-fetch@1.7.3

现在您可以使用下面的行而不会出现错误。

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

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

npm install --save isomorphic-fetch es6-promise

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

import "isomorphic-fetch"

最好的是用于获取的Axios库。 使用NPM I -保存axios用于安装,并像fetch一样使用它,只需编写axios而不是fetch,然后在then()中获得响应。