ReferenceError:未定义fetch

jas*_*704 98 javascript node.js

我在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);
  });   
}
Run Code Online (Sandbox Code Playgroud)

Adr*_*n T 171

获取API未在节点中实现.

你需要使用一个外部模块,一个好的是节点获取.

如下所示将其安装在Node应用程序中

npm i node-fetch --save
Run Code Online (Sandbox Code Playgroud)

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

const fetch = require("node-fetch");
Run Code Online (Sandbox Code Playgroud)

  • `var`是可以改变的,我建议使用`const`代替...... (14认同)
  • 按照这些说明,我必须使用“.mjs”扩展名保存文件才能使其正常工作。 (8认同)
  • Fetch API [已在 Node 中实现](https://github.com/nodejs/node/pull/41749),并且应该[在一年左右](https://news.ycombinator.com/item) 发布?id=30161964)。 (8认同)
  • 真的应该标记为答案吗? (2认同)
  • 2022 年更新:Node 发布了“node version 18”,它允许您使用 fetch,而无需任何额外的软件包(如“node-fetch”)。 (2认同)

小智 21

fetch在实验标志下来到 Node v17--experimental-fetch

它将在没有该标志的 Node v18 中可用。

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

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

  • Node 18 已发布,仍处于实验阶段。 (6认同)
  • 我在本地环境中使用节点 v 18,并且“fetch”只能在服务器上运行。但在 v18 的 Netlify 上它不起作用。我需要节点获取。 (2认同)

Lor*_*lor 19

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

global.fetch = require("node-fetch");
Run Code Online (Sandbox Code Playgroud)

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

  • 这是我能够让 WebStorm 识别由 `fetch` 返回的承诺并自动完成可用方法的唯一方法。同意在生产中应该避免它,但对本地开发非常有帮助! (2认同)

Raf*_*nço 16

编辑 - 新解决方案

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

const fetch = (url) => import('node-fetch').then(({default: fetch}) => fetch(url));
Run Code Online (Sandbox Code Playgroud)

旧答案:

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

npm install node-fetch@1.7.3
Run Code Online (Sandbox Code Playgroud)

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

const fetch = require("node-fetch");
Run Code Online (Sandbox Code Playgroud)


Ric*_*gis 11

您可以从@lquixada使用交叉获取

平台无关:浏览器,节点或本机响应

安装

npm install --save cross-fetch
Run Code Online (Sandbox Code Playgroud)

用法

承诺:

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);
  });
Run Code Online (Sandbox Code Playgroud)

使用异步/等待:

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);
  }
})();
Run Code Online (Sandbox Code Playgroud)


ofi*_*hai 11

您应该在文件中添加此导入:

import * as fetch from 'node-fetch';
Run Code Online (Sandbox Code Playgroud)

然后,运行此代码以添加node-fetch
$ yarn add node-fetch

如果您正在使用打字稿,请安装 node-fetch 类型:
$ yarn add @types/node-fetch

  • 如果我以这种方式导入并使用打字稿,则会出现此错误`TS2349:此表达式不可调用。类型 'typeof import("/node_modules/@types/node-fetch/index")' 没有调用签名。`。它仅适用于“require”。 (4认同)

Khu*_*iaz 10

如果你想避免 npm install 而不是在浏览器中运行,你也可以使用 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);
})
Run Code Online (Sandbox Code Playgroud)

  • 只需记住在此代码段的底部添加 `.end()` 即可实际启动请求。请参阅[文档](https://nodejs.org/api/http.html#http_request_end_data_encoding_callback) (2认同)

Mig*_*llo 8

Node.js 尚未实现 fetch() 方法,但您可以使用这个奇妙的 JavaScript 执行环境的外部模块之一。

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

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

npm i node-fetch --save

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

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


Ame*_*icA 7

您必须将该isomorphic-fetch模块用于您的Node项目,因为Node尚未包含Fetch API。要解决此问题,请运行以下命令:

npm install --save isomorphic-fetch es6-promise
Run Code Online (Sandbox Code Playgroud)

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

import "isomorphic-fetch"
Run Code Online (Sandbox Code Playgroud)

希望这个回答对你有帮助。

  • 未积极维护;距离上次接受 PR 已经有好几年了。https://github.com/matthew-andrews/isomorphic-fetch/graphs/contributors (9认同)

Moh*_*nit 6

最好的一个是用于获取的 Axios 库。使用npm i --save axios了installng和使用它像取,只写爱可信的,而不是获取,然后得到响应则()


clo*_*oop 5

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

npm install 这些软件包:

    "amazon-cognito-identity-js": "3.0.11"
    "node-fetch": "^2.3.0"
Run Code Online (Sandbox Code Playgroud)

然后包括:

    "amazon-cognito-identity-js": "3.0.11"
    "node-fetch": "^2.3.0"
Run Code Online (Sandbox Code Playgroud)

  • `amazon-cognito-identity-js`与该问题无关,不需要安装即可解决此错误。它也与打字稿无关。 (5认同)

小智 5

对于 CORS 请求,似乎使用“http”或“https”获取支持 URL 方案。

安装 node fetch 库npm install 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))
Run Code Online (Sandbox Code Playgroud)


nab*_*ais 5

在 HackerRank 中,有些库是默认安装的,有些则不是。

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

您要做的最好的事情是检查库是否已安装。

在练习的顶部,有以下内容:

const https = require('https');
Run Code Online (Sandbox Code Playgroud)

请尝试将其添加到顶部:

const axios = require('axios');
Run Code Online (Sandbox Code Playgroud)

然后运行代码。

如果出现编译错误,那么它不可用,否则你可以使用axios,这是一个很好的替代方案fetch

要将其与 一起使用then,您可以:

function getMovieTitles(substr){
  axios.get(url)
    .then(function(response){
      console.log(response.data);
    })
}
Run Code Online (Sandbox Code Playgroud)

或利用async/await

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


小智 5

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

npm i node-fetch
Run Code Online (Sandbox Code Playgroud)

然后 :

import fetch from 'node-fetch';
Run Code Online (Sandbox Code Playgroud)

这是 (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();
Run Code Online (Sandbox Code Playgroud)