Have you ever tried to fetch something in NodeJS and found out that the fetch API doesn't work? If you have experienced this, you are not alone. Fetch is a browser API, and NodeJS doesn't have it. To fetch data in NodeJS, you will have to use the built-in http
or the https
module.
const https = require("https");
const url = "https://jsonplaceholder.typicode.com/posts";
https
.get(url, (res) => {
let response = "";
res.on("data", (chunk) => {
response += chunk;
});
res.on("end", () => {
try {
let json = JSON.parse(body); // do something with JSON
} catch (error) {
console.error(error.message);
}
});
})
.on("error", (error) => {
console.error(error.message);
});
If you don't like the verbose syntax of the https
module, then don't worry. Some great devs have made the node-fetch
npm package for you.
node-fetch
The node-fetch
package is a lightweight module that brings the power of the fetch
API in NodeJS. To install it, run-
# yarn
yarn add node-fetch
# npm
npm i node-fetch
Then you can import it in a Node JS file and use it as you usually do.
const fetch = require("node-fetch");
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
const json = await response.json();
The node-fetch
package is a replication of fetch
for Node JS. So, it includes all the methods and also supports the options object. For example-
const fetch = require("node-fetch");
const url = "https://jsonplaceholder.typicode.com/posts";
const options = {
method: "Get",
};
const response = await fetch(url, options);
const json = await response.json();
Conclusion
Though Node JS includes two powerful built-in modules for data fetching, their syntax is over-complicated. And for the dev who love the simple syntax of the fetch
API, some awesome people have come up with the node-fetch
package. It's not only easy to use but also a fast and lightweight solution.
Leave a comment