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)
小智 21
fetch
在实验标志下来到 Node v17--experimental-fetch
它将在没有该标志的 Node v18 中可用。
https://github.com/nodejs/node/pull/41749#issue-1118239565
您不再需要安装任何额外的软件包
Lor*_*lor 19
如果必须在全局范围内访问它
global.fetch = require("node-fetch");
Run Code Online (Sandbox Code Playgroud)
这是一个快速的肮脏修复程序,请尝试消除生产代码中的用法。
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
平台无关:浏览器,节点或本机响应
安装
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
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)
Node.js 尚未实现 fetch() 方法,但您可以使用这个奇妙的 JavaScript 执行环境的外部模块之一。
在上面的一个答案中,引用了“node-fetch”,这是一个不错的选择。
在您的项目文件夹(您拥有 .js 脚本的目录)中,使用以下命令安装该模块:
npm i node-fetch --save
然后将其用作要使用 Node.js 执行的脚本中的常量,如下所示:
const fetch = require("node-fetch");
您必须将该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)
希望这个回答对你有帮助。
对于那些也在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)
小智 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)
在 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)
归档时间: |
|
查看次数: |
78080 次 |
最近记录: |