Javascript 参考错误:未定义提取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48433783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReferenceError: fetch is not defined
提问by jasa1704
I have this error when I compile my code in node.js, how can I fix it?
在 node.js 中编译代码时出现此错误,我该如何解决?
RefernceError: fetch is not defined
引用错误:未定义提取
This is the function I am doing, it is responsible for recovering information from a specific movie database.
这是我正在做的功能,它负责从特定的电影数据库中恢复信息。
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);
});
}
回答by Adrian T
The fetch APIis not implemented in Node.
在获取API未在节点中实现。
You need to use an external module for that, like node-fetch.
您需要为此使用外部模块,例如node-fetch。
Install it in your Node application like this
像这样将其安装在您的 Node 应用程序中
npm i node-fetch --save
then put the line below at the top of the files where you are using the fetch API:
然后将下面的行放在您使用 fetch API 的文件的顶部:
const fetch = require("node-fetch");
回答by Lorem Ipsum Dolor
If it has to be accessible with a global scope
如果它必须可以在全局范围内访问
global.fetch = require("node-fetch");
This is a quick dirty fix, try to eliminate the usage in production code.
这是一个快速的肮脏修复,尝试消除生产代码中的使用。
回答by Richard Vergis
You can use cross-fetchfrom @lquixada
您可以使用来自@lquixada 的交叉提取
Platform agnostic: browsers, node or react native
平台不可知:浏览器、节点或本机反应
Install
安装
npm install --save cross-fetch
Usage
用法
With promises:
承诺:
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);
});
With async/await:
使用异步/等待:
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);
}
})();
回答by closedloop
For those also using typescripton node-jsand are getting a ReferenceError: fetch is not definederror
对于那些也在node-js上使用typescript并且遇到错误的人ReferenceError: fetch is not defined
npm installthese packages:
npm install这些包:
"amazon-cognito-identity-js": "3.0.11"
"node-fetch": "^2.3.0"
Then include:
然后包括:
import Global = NodeJS.Global;
export interface GlobalWithCognitoFix extends Global {
fetch: any
}
declare const global: GlobalWithCognitoFix;
global.fetch = require('node-fetch');
回答by Mohammad Quanit
Best one is Axios library for fetching.
use npm i --save axiosfor installng and use it like fetch, just write axios instead of fetch and then get response in then().
最好的一个是用于获取的 Axios 库。使用npm i --save axios了installng和使用它像取,只写爱可信的,而不是获取,然后得到响应则() 。
回答by AmerllicA
You have to use the isomorphic-fetchmodule to your Nodeproject because of Nodedoes not contain Fetch APIyet. for fixing this problem run below command:
您必须将该isomorphic-fetch模块用于您的Node项目,因为Node尚未包含Fetch API。要解决此问题,请运行以下命令:
npm install --save isomorphic-fetch es6-promise
After installation use below code in your project:
安装后在您的项目中使用以下代码:
import "isomorphic-fetch"
Hope this answer helps you.
希望这个回答对你有帮助。
回答by Miguel Murillo
Node.js hasn't implemented the fetch() method, but you can use one of the external modules of this fantastic execution environment for JavaScript.
Node.js 尚未实现 fetch() 方法,但您可以使用这个奇妙的 JavaScript 执行环境的外部模块之一。
In one of the answers above, "node-fetch" is cited and that's a good choice.
在上面的一个答案中,引用了“node-fetch”,这是一个不错的选择。
In your project folder (the directory where you have the .js scripts) install that module with the command:
在您的项目文件夹(您拥有 .js 脚本的目录)中,使用以下命令安装该模块:
npm i node-fetch --save
npm i node-fetch --save
Then use it as a constant in the script you want to execute with Node.js, something like this:
然后将其用作要使用 Node.js 执行的脚本中的常量,如下所示:
const fetch = require("node-fetch");
const fetch = require("node-fetch");


