0
0
NodejsHow-ToBeginner · 3 min read

How to Use node-fetch in Node.js: Simple Guide

To use node-fetch in Node.js, first install it with npm install node-fetch. Then import it using import fetch from 'node-fetch' and call fetch(url) to make HTTP requests and handle responses with promises or async/await.
📐

Syntax

The basic syntax to use node-fetch involves importing the fetch function and calling it with a URL. It returns a promise that resolves to a response object.

  • import fetch from 'node-fetch': Imports the fetch function.
  • fetch(url, options): Makes a request to the URL with optional settings.
  • response.json(): Parses the response body as JSON.
javascript
import fetch from 'node-fetch';

const url = 'https://api.example.com/data';

fetch(url, {
  method: 'GET', // HTTP method
  headers: { 'Content-Type': 'application/json' } // Optional headers
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
💻

Example

This example shows how to fetch JSON data from a public API using async/await syntax. It prints the data to the console.

javascript
import fetch from 'node-fetch';

async function getData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

getData();
Output
{ userId: 1, id: 1, title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', body: 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto' }
⚠️

Common Pitfalls

Common mistakes when using node-fetch include:

  • Not installing the package before importing it.
  • Using require instead of import in ESM projects.
  • Forgetting to check response.ok before parsing the response.
  • Not handling network errors with catch or try/catch.
javascript
/* Wrong: Using require in ESM or forgetting to install */
// const fetch = require('node-fetch'); // This may cause errors in ESM projects

/* Right: Use import and check response */
import fetch from 'node-fetch';

async function fetchData() {
  const response = await fetch('https://api.example.com');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  const data = await response.json();
  return data;
}
📊

Quick Reference

Summary tips for using node-fetch:

  • Install with npm install node-fetch.
  • Use import fetch from 'node-fetch' in modern Node.js.
  • Always check response.ok before parsing.
  • Handle errors with try/catch or .catch().
  • Use async/await for cleaner asynchronous code.

Key Takeaways

Install node-fetch with npm before using it in your Node.js project.
Import fetch using ESM syntax: import fetch from 'node-fetch'.
Always check response.ok to handle HTTP errors properly.
Use async/await for easier and cleaner asynchronous code.
Handle network errors with try/catch or promise catch blocks.