ReferenceError:提取未定义


177

在node.js中编译代码时出现此错误,该如何解决?

RefernceError:提取未定义

在此处输入图片说明

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

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

4
欢迎使用SO,请提供到目前为止您尝试过的详细信息?请在需要时提供最小,完整和可验证的示例。另请花些时间阅读“ 如何提问”
Pratibha

3
fetch不是标准的nodejs方法-您需要node-fetch
Jaromanda X

3
fetch()是为浏览器设计的,然后在显然不见的第三方模块中反向移植到node.js。该request()request-promise()库更多本地专为node.js的支持更广泛的使用Node.js语言,包括溪流,数不胜数的认证方法等选项...
jfriend00

Answers:


316

获取API未在节点中实现。

为此,您需要使用一个外部模块,例如node-fetch

像这样将其安装在您的Node应用程序中

npm i node-fetch --save

然后将下面的行放在使用fetch API的文件顶部:

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

21
var是可变的,我建议const应该改用...
Edwin Pratt

3
@ jasa1704您能选择一个答案吗?
tecnocrata

36

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

global.fetch = require("node-fetch");

这是一个快速的肮脏修复程序,请尝试消除生产代码中的用法。


1
这是使WebStorm能够识别返回的诺言fetch并自动完成可用方法的唯一方法。同意在生产中应避免使用它,但对本地开发人员非常有帮助!
FoxMulder900 '18 -10-7

18

您可以从@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);
  }
})();

这对metaweather api有所帮​​助,在github文档中有很好的解释。感谢您的分享
krupesh Anadkat

使用crossfetch的polyfill也可以使用typescript和node并ReferenceError: fetch is not defined从接收错误amazon-cognito-identity-js
John Hamelink,

7

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

npm install 这些软件包:

    "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');

28
amazon-cognito-identity-js与该问题无关,无需安装即可解决此错误。它也与打字稿无关。
cnvzmxcvmcx

嗨!所以我遇到了完全相同的问题,但这仍然无法解决任何问题,您还有其他解决方法吗?
Masnad Nihit



4

Node.js尚未实现fetch()方法,但是您可以将这种出色的执行环境的外部模块之一用于JavaScript。

在以上答案之一中,引用了“ node-fetch”,这是一个不错的选择。

在项目文件夹(包含.js脚本的目录)中,使用以下命令安装该模块:

npm我节点获取-保存

然后将其用作要使用Node.js执行的脚本中的常量,如下所示:

const fetch = require(“ node-fetch”);


1

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


0

以下在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>
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.