In HackerRank, some libraries are installed by default and some are not.
Because it is running Node.js, the fetch API is not installed by default.
The best thing for you to do is to check whether the libraries are or not installed.
on the top of the exercise, there is the following:
const https = require('https');
Please try to add this to the top as well:
const axios = require('axios');
and then run the code.
If there is a compilation error, then it’s not available, otherwise you can use axios
, which is a good alternative to fetch
To use it with then
, you can:
function getMovieTitles(substr){
axios.get(url)
.then(function(response){
console.log(response.data);
})
}
or taking advantage of the async/await
async function getMovieTitles(substr){
let response = await axios.get(url)
console.log(response.data);
}
In this blog post, we’ll tackle the common issue of encountering a «ReferenceError: fetch is not defined» error when working with JavaScript, specifically Node.js. This error typically occurs when you try to use the fetch API in a Node.js environment. While the fetch API is natively available in modern browsers, it is not built into older versions of Node.js. As a developer, understanding how to resolve this issue will help you effectively work with web APIs and improve your overall knowledge of JavaScript and Node.js.
Understanding the fetch API
Before diving into the solution, let’s first understand what the fetch API is and why it’s important. The fetch API is a modern, flexible, and powerful approach to making HTTP requests in JavaScript. It provides a simple and efficient way to fetch resources, including across the network. The fetch API is built on top of the Promise API, making it easy to work with asynchronous operations and handle errors gracefully.
The Problem: ReferenceError: fetch is not defined
As mentioned earlier, the fetch API is natively available in modern browsers but is not included in older versions of Node.js. If you try using the fetch API directly in Node.js, you’ll encounter the «ReferenceError: fetch is not defined» error. This error occurs because Node.js does not have a built-in fetch implementation.
Fixing the Issue
To fix the «ReferenceError: fetch is not defined» error, you can use the popular node-fetch
package, which provides a lightweight fetch implementation for Node.js. The package can be easily installed via npm or yarn.
Step 1: Installing node-fetch
To install the node-fetch
package, open your terminal, navigate to your project directory, and run the following command:
For npm users:
npm install node-fetch
For yarn users:
yarn add node-fetch
If you use an older Node.js version, you should install version 2 of the node-fetch
package with the following command:
npm install node-fetch@2
Step 2: Importing and using node-fetch
Once the installation is complete, you can import and use node-fetch
in your Node.js project. To do this, add the following line to your JavaScript file:
For CommonJS syntax:
const fetch = require('node-fetch');
For ES6 Modules syntax:
import fetch from 'node-fetch';
Note that the more recent versions of the node-fetch
package are only compatible with the ES6 Modules syntax of import/export. If you encounter issues with the import statement, make sure to check your Node.js version and ensure that your project is configured correctly to utilize ES6 modules.
With node-fetch
imported, you can now use the fetch API just like you would in a browser environment.
Here’s an example of using node-fetch
to make a simple GET request:
const fetch = require('node-fetch'); fetch('https://api.codedamn.com/some-endpoint') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
In this example, we’re fetching data from an API endpoint and then logging the response to the console. If the request is successful, we’ll see the fetched data in the console. If there’s an error, we’ll log the error message.
FAQ
Q: Can I use other libraries or packages instead of node-fetch?
A: Yes, there are several other libraries and packages available that provide similar functionality, such as axios
, got
, request
, and superagent
. You can choose the library that best suits your needs and preferences.
Q: How can I use async/await with fetch in Node.js?
A: To use async/await with fetch in Node.js, you can simply create an async function and use the await
keyword when calling the fetch API. Here’s an example:
const fetch = require('node-fetch'); async function fetchData() { try { const response = await fetch('https://api.codedamn.com/some-endpoint'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } fetchData();
Q: How can I make POST requests using fetch in Node.js?
A: To make a POST request using fetch in Node.js, you need to provide an additional options
object with the method
, headers
, and body
properties. Here’s an example:
const fetch = require('node-fetch'); const postData = { key1: 'value1', key2: 'value2', }; fetch('https://api.codedamn.com/some-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData), }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
In this example, we’re sending a JSON object as the request body. Make sure to set the Content-Type
header accordingly if you’re sending data in a different format.
Q: How can I handle fetch errors effectively?
A: The fetch API does not reject the promise on HTTP errors like 404 or 500. Instead, it only rejects the promise on network errors. To handle HTTP errors, you can check the response.ok
property and throw an error if it’s false. Here’s an example:
const fetch = require('node-fetch'); fetch('https://api.codedamn.com/some-endpoint') .then(response => { if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
In this example, we’re checking the response.ok
property and throwing an error with the HTTP status code if it’s false. The error will be caught and logged in the catch block.
Conclusion
We hope this blog post has helped you understand and fix the «ReferenceError: fetch is not defined» error in Node.js. By using the node-fetch
package or an alternative library, you can effectively work with the fetch API in your Node.js projects. Be sure to explore the official node-fetch documentation for more information and advanced usage. Happy coding!
Become The Best Full-Stack Developer 🚀
Codedamn is the best place to become a proficient developer. Get access to hunderes of practice Node.js courses, labs, and become employable full-stack web developer.
Free money-back guarantee
Unlimited access to all platform courses
100+ practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured Node.js Full-Stack Roadmap To Get A Job
Exclusive community for events, workshops
Start Learning
What is Node.js?
Node.js, the open-source server environment, has become very popular for generating dynamic page content. It can create, read, write, and delete files on the server. Moreover, it collects, adds, deletes, and modifies data in your database. Using an asynchronous approach, Node.js significantly reduces waiting times compared to other backend web technologies.
How Node.js handles a file request?
- By sending the task to the computer’s file system.
- By being ready to handle the subsequent request
- By enabling the server to return the content to the client when the file system has opened and read the file
Benefits of Node.js
- Enable coding in JavaScript for Client and server side
- Very fast at building high-traffic applications
- Plenty of tools and modules
- Suitable for various industries
- Super-fast performance
- Scalability
What is Fetch API?
Fetch() is a widely liked cross-platform HTTP client API that runs in browsers and Web/Service Workers. It offers a JavaScript interface for interacting with and accessing protocol elements like requests and answers. For example, the fetch () method jolts the process of fetching a resource from a server. This kind of functionality was earlier completed using XMLHttpRequest. FetchAPI is based on async and await.
What is Fetch Async & Await?
Async functions are available natively in Node and are denoted by the async keyword in their declaration. They always return a promise, even if you don’t explicitly write them to do so. Also, the await keyword is only available inside async functions at the moment – it cannot be used in the global scope.
In an async function, you can await any Promise or catch its rejection cause.
The async and await keywords enable asynchronous, promise-based behaviour to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
This version of the example could be simpler to comprehend:
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
myDisplay(y);
}
(Ref: https://www.w3schools.com/jsref/api_fetch.asp )
If you are a Node JS developer, you must have tried getting the data from an API in Node.js using Fetch. And most likely, you have encountered the following error.
ReferenceError: fetch is not defined
There is no Fetch in Node.js
This happens because Fetch doesn’t work in Node.js. As the Fetch API is not implemented in Node, it is necessary to use a package to implement and use it. So, if you have a team of Node JS Developers from the best company, you must manifest the solution for using Fetch in Node.js.
What is the solution?
If your project does not have a package.json file, create one in your project’s root directory:
npm init -y
Now install the node-fetch library.
npm install node-fetch
Now you can import and use the module just like the fetch() method in the browser.
import fetch from ‘node-fetch’;
async function getUser() {
try {
const response = await fetch(‘https://randomuser.me/api/’);
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
return result;
} catch (err) {
console.log(err);
}
}
console.log(await getUser());
At the time of writing, you have to set the type property to the module in your package.json file to use ES6 module imports and exports in a NodeJs project.
{
«type»: «module»,
// … rest
}
If you run Nodejs script, you will get the result from calling the API.
ReferenceError fetch is not defined in NodeJs (older versions)
Only do the following if you have older version of Nodejs and need to use the ‘require’ syntax instead of ‘import/export’
npm install node-fetch@2
Version 2 of the node-fetch package was set up. Make sure you do not have the type property set in your module. The old require method can now be used to import the fetch package.
Use older require syntax
const fetch = require(‘node-fetch’);
async function getUser() {
try {
const response = await fetch(‘https://randomuser.me/api/’);
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
return result;
} catch (err) {
console.log(err);
}
}
It’s best to keep your client-side and server-side code’s imports consistent. Nevertheless, this strategy works if you need to support an earlier version of NodeJs.
Code Ref- https://bobbyhadz.com/blog/javascript-referenceerror-fetch-is-not-defined
Why Utilize the Node.js Fetch API?
To help the developer community, the fetch API is offered as a pre-configured Node module, and the benefits of it are;
- Cross-platform Familiarity
- Faster Implementation
- No Additional Fetch Packages
With the new launch, Fetch is now available as an experimental feature in Node v17. Suppose you want to try its trial version before the major release; download and upgrade the node.js version to 17.5. Then, hire a Node js developer who is well abreast with the regular updates and changes introduced in the market to harness the power of Fetch in Node.js.
About Author
ManekTech Team
ManekTech is a well-known software development and IT consulting company, providing custom software, website, and mobile app development services. ManekTech has own content writing and development team who writes content on various and trending technology that it serves currently.
Table of Contents
Have you been a front-end developer and recently started using Node.js?
Have you used fetch
to get the data from an API in Node.js the way you do in the front-end?
Then most likely you would have encountered the following error:
1ReferenceError: fetch is not defined
Replicating the issue
First, let’s replicate the issue.
You can update the index.js
to the following and run node index.js
, you should be able to see the error.
index.js
1const fetchRandomUser = () => {
2 fetch("https://randomuser.me/api/").then(async response => {
3 const data = await response.json()
4 console.log({ data })
5 })
6}
7
8fetchRandomUser()
Understanding the issue
Why does the above code work perfectly fine in the front-end (or browser) and fails in Node.js?
This is because fetch is a Web API and it is not supported in the version of the Node.js installed on your machine.
Fixing the issue
There are 2 ways in which you can fix this issue:
Upgrading Node.js to v18 or later
Starting version 18, Node.js has started supporting fetch API.
You can download the latest Node.js version from here and install it.
Using node-fetch library
Previous to the release of Node.js v18, the most popular way to use fetch in Node.js is to install the node-fetch library.
Let’s go ahead and do it.
Now update the index.js
to import fetch
:
1import fetch from "node-fetch"
2
3const fetchRandomUser = () => {
4 fetch("https://randomuser.me/api/").then(async response => {
5 const data = await response.json()
6 console.log({ data })
7 })
8}
9
10fetchRandomUser()
Note that we have used the import syntax because starting v3, node-fetch
is an ESM only module.
If you are using Node.js version earlier than 12.20.0 or need to use CommonJS syntax (require syntax: const fetch = require("node-fetch")
),
then you can install node-fetch version 2 using npm i [email protected]
.
Update the package.json
with type
as module
.
This is required to tell Node.js to use ESM Module syntax, since, by default, Node.js uses CommonJS syntax.
1{
2 "name": "nodejs-referenceerror-fetch-is-not-defined",
3 "version": "1.0.0",
4 "description": "",
5 "main": "index.js",
6 "type": "module",
7 "scripts": {
8 "test": "echo "Error: no test specified" && exit 1"
9 },
10 "keywords": [],
11 "author": "",
12 "license": "ISC",
13 "dependencies": {
14 "node-fetch": "^3.2.9"
15 }
16}
Now if you run the code, it should work properly.
If you have liked article, do follow me on twitter to get more real time updates!
While you are working with NodeJS and trying to fetch API from a server to work with, you might get the error “reference error fetch is not defined” in NodeJS. So, why does this happen, and how to solve it? Let’s go into detail.
The cause of this error
This error happens because the fetch method works in an environment that doesn’t support the most commonly NodeJS. If you want to work with ‘fetch’ method, you will have to download ‘node-fetch’ package that provides ‘fetch’ method and then import it into your project.
An example of the error:
import http from "http";
const server = http.createServer(function (req, res) {
res.end("Hello From the server");
});
server.listen(8000, function () {
console.log("Server is running at 8000");
});
fetch("https://dog.ceo/api/breeds/image/random", {
method: "GET",
})
.then((res) => res.json())
.then((json) => {
console.log(json);
});
The error:
ReferenceError: fetch is not defined
Importing the fetch method through node-fetch is the best way to solve the error “reference error fetch is not defined” in NodeJS.
If you want to install ‘node-fetch’, your project has to have ‘package.json’ file. If you not, you can create one by this command :
npm init
The result :
Now you can install node-fetch with the command:
npm install node-fetch
Or with shortcut:
npm i node-fetch
The result :
Then you can import it and use it in your project.
Example :
import fetch from "node-fetch";
import http from "http";
const server = http.createServer(function (req, res) {
res.end("Hello From the server");
});
server.listen(8000, function () {
console.log("Server is running at 8000");
});
fetch("https://dog.ceo/api/breeds/image/random", {
method: "GET",
})
.then((res) => res.json())
.then((json) => {
console.log(json);
});
Output :
Server is running at 8000
{
message: 'https://images.dog.ceo/breeds/komondor/n02105505_1159.jpg',
status: 'success'
}
Then you can work with JSON that is server responsive.
This is how you do it in new versions.
Summary
In this tutorial, I explained how to solve the error “Reference error fetch is not defined” in NodeJS. I hope you will enjoy it. If you have any questions about this error, please comment below. Thanks for your reading!
Maybe you are interested:
- Npm WARN old lockfile The package-lock.json file was created with an old version of npm
- Create React App requires Node 14 or higher. Please update your version of Node
- Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist
Hello, guys! I hope that my knowledge in HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, Python, MySQL, and npm computer languages may be of use to you. I’m Brent Johnson, a software developer.
Name of the university: HOU
Major: IT
Programming Languages: HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, PyThon, MySQL, npm