ReferenceError: fetch 未定义 [英] ReferenceError: fetch is not defined
本文介绍了ReferenceError: fetch 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 node.js 中编译代码时出现此错误,我该如何解决?
I have this error when I compile my code in node.js, how can I fix it?
ReferenceError: fetch 未定义
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);
});
}
推荐答案
fetch API 未在 Node 中实现.
The fetch API is not implemented in Node.
您需要为此使用外部模块,例如 node-fetch.
You need to use an external module for that, like node-fetch.
像这样将其安装在您的 Node 应用程序中
Install it in your Node application like this
npm install node-fetch
然后将下面的行放在您使用 fetch API 的文件的顶部:
then put the line below at the top of the files where you are using the fetch API:
import fetch from "node-fetch";
这篇关于ReferenceError: fetch 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文