Node.js beginner 15 min

fetch()

Learn about fetch() in Node.js.

fetch() in Node.js

fetch() is a function that lets your code make HTTP requests to other servers or APIs. In modern JavaScript and Node.js, you can use fetch() to get data from a URL.

Why Use fetch()?

Before fetch(), developers used libraries or other functions. fetch() is now built into modern environments and is easy to use.

Basic Example

This example fetches data from a JSON placeholder API:

const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data);

How It Works

  1. fetch() sends a request to the URL.
  2. The server sends back a Response object.
  3. response.json() converts the response body into a JavaScript object.
  4. You can then use the data in your code.

POST Request Example

You can also send data to a server using POST:

const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "My Post", body: "Hello World" })
});
const data = await response.json();
console.log(data);

Practice

Write a small program that fetches a random user from https://jsonplaceholder.typicode.com/users/1 and prints the user name.

Common Mistake

Forgetting to use await when calling response.json() can result in unexpected data. Always use await for asynchronous fetch calls.