0
0
NodejsHow-ToBeginner · 3 min read

How to Use Fetch in Node.js: Simple Guide with Examples

In Node.js (version 18 and above), you can use the built-in fetch function to make HTTP requests just like in browsers. Simply call fetch(url) and handle the response with async/await to get data from APIs or websites.
📐

Syntax

The fetch function takes a URL string as the first argument and an optional options object as the second argument. It returns a Promise that resolves to a Response object.

  • url: The web address you want to request.
  • options: Optional settings like method (GET, POST), headers, and body.
  • Response: The result object you can use to read data like JSON or text.
javascript
const response = await fetch(url, options);
const data = await response.json();
💻

Example

This example shows how to fetch JSON data from a public API and print a value from the response.

javascript
async function getUser() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  const user = await response.json();
  console.log('User name:', user.name);
}

getUser().catch(console.error);
Output
User name: Leanne Graham
⚠️

Common Pitfalls

  • Not using await or .then() to handle the asynchronous fetch call.
  • Forgetting to check response.ok to handle HTTP errors.
  • Trying to use fetch in Node.js versions before 18 without installing a package.
  • Not parsing the response body with response.json() or response.text().
javascript
/* Wrong: Missing await and error check */
fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => response.json())
  .then(data => console.log(data.name));

/* Right: Using await and error check */
async function fetchUser() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  if (!response.ok) {
    throw new Error('Failed to fetch');
  }
  const data = await response.json();
  console.log(data.name);
}
fetchUser();
📊

Quick Reference

Remember these key points when using fetch in Node.js:

  • Node.js 18+ has built-in fetch, no extra install needed.
  • Use await to wait for the response.
  • Check response.ok to catch errors.
  • Parse response with response.json() or response.text().
  • For older Node.js versions, use node-fetch package.

Key Takeaways

Node.js 18+ includes a built-in fetch function similar to browsers.
Always use async/await and check response.ok to handle errors.
Parse the response body with response.json() or response.text() before use.
For Node.js versions before 18, install and import the node-fetch package.
Fetch is a simple way to make HTTP requests without extra libraries in modern Node.js.