I have this error when I compile my code in node.js, how can I fix it?
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);
});
}
For those also using typescript on node-js and are getting a
ReferenceError: fetch is not defined
errornpm install
these packages:Then include:
Best one is Axios library for fetching. use
npm i --save axios
for installng and use it like fetch, just write axios instead of fetch and then get response in then().You have to use the
isomorphic-fetch
module to yourNode
project because ofNode
does not containFetch API
yet. for fixing this problem run below command:After installation use below code in your project:
Hope this answer helps you.
The fetch API is not implemented in Node.
You need to use an external module for that, like node-fetch.
Install it in your Node application like this
then put the line below at the top of the files where you are using the fetch API:
If it has to be accessible with a global scope
This is a quick dirty fix, try to eliminate the usage in production code.
You can use cross-fetch from @lquixada
Install
Usage
With promises:
With async/await: