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

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

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

npm install node-fetch

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

import fetch from "node-fetch";

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

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

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

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

npm install --save isomorphic-fetch es6-promise

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

import "isomorphic-fetch"

你可以使用@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);
  }
})();

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


对于那些也在node-js上使用typescript并得到ReferenceError: fetch is not defined错误的人

NPM安装这些包:

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

然后包括:

import Global = NodeJS.Global;
export interface GlobalWithCognitoFix extends Global {
    fetch: any
}
declare const global: GlobalWithCognitoFix;
global.fetch = require('node-fetch');

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

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

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

npm i node-fetch --save

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

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

这是相关的github问题 此错误与2.0.0版本有关,您可以通过简单地升级到2.1.0版本来解决它。 你可以跑 NPM I graphql-request@2.1.0-next.1


下面的工作为我在Node.js 12.x:

npm i node-fetch;

初始化Dropbox实例:

var Dropbox = require("dropbox").Dropbox;
var dbx = new Dropbox({
   accessToken: <your access token>,
   fetch: require("node-fetch")    
});

例如,上传一个内容(在这种情况下使用异步方法):

await dbx.filesUpload({
  contents: <your content>,
  path: <file path>
});

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

import * as fetch from 'node-fetch';

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

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


如果你想避免npm安装而不能在浏览器中运行,你也可以使用nodejs的https模块;

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

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


它似乎获取支持URL方案与“http”或“https”的CORS请求。

安装node-fetch库,读取文件并解析为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))

在HackerRank中,有些库默认安装,有些没有安装。

因为它运行的是Node.js,所以默认情况下不会安装获取API。

最好的方法是检查是否安装了库。

在练习的顶部,有以下几点:

const https = require('https');

请试着把这个也添加到顶部:

const axios = require('axios');

然后运行代码。

如果存在编译错误,则不可用,否则可以使用axios,这是获取的一个很好的替代方法

要使用它,你可以:

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

或者利用async/await

async function getMovieTitles(substr){
  let response = await axios.get(url)
  console.log(response.data);
}

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

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

实际上有很多不同的库可以在浏览器中获取。

我所知道的主要问题有:

node-fetch cross-fetch whatwg-fetch isomorphic-fetch

我目前使用节点获取,它工作得很好,但我真的不知道哪一个是“最好的”。(尽管我链接的openbase.com页面提供了一些使用情况的元数据。Github星,npm下载],这可以帮助)


在node.js中,你可以使用:node-fetch包

npm i node-fetch

然后:

import fetch from 'node-fetch';

以下是(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();

编辑-新的解决方案

要使用最新版本(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");

只要把你的app.js文件扩展为app.mjs,问题就会解决!!:)


如需安装:

npm install --save global-fetch

then

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

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

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

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

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


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

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

尝试使用axios包:

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

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

这招对我很管用:

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

npm i node-fetch 

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

import fetch from "node-fetch";

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

"type": "module"