AI Hints
Home›JavaScript Tutorial›Promise.all and fetch
JavaScript · Lesson 86 of 138

fetch

Data from a server.

⏱ 2 min read▶ Video at 1:43:47🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Fetch is how JavaScript asks a server for data. It works in every browser, and in Node too. You give it a web address, and it returns a promise for the response.

fetch
From the video: fetch
  • Ask a server for data
  • Browsers and Node
  • Returns a promise

Fetching JSON

To keep this example self contained, the first lines start a tiny local server that sends back JSON. Then fetch asks it for the users. The response arrives first, with a status code. Then response dot json reads the body, which is also a promise. Run it.

app.mjsjavascript
import http from "node:http";
const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify([{ name: "Ana" }, { name: "Ben" }]));
}).listen(3000);

const response = await fetch("http://localhost:3000/users");
console.log("Status:", response.status, response.ok);

const users = await response.json();
console.log(users.map(u => u.name));
server.close();
Output
Status: 200 true
[ 'Ana', 'Ben' ]

The steps of a request

First, fetch sends the request. Then the response arrives, with a status code like two hundred for o k, or four oh four for not found. Then you read the body, as JSON, or as text. Each step takes time, so each one returns a promise you await.

keyvalue
await fetch(url)the response
response.status200, 404, 500...
response.oktrue for 200–299
await response.json()the data

Summary

Fetch requests data from a server. Await the response, check its status, then await response dot json. Next, handling fetch errors properly.

Key takeaways
  • await fetch(url)
  • Check response.ok
  • await response.json()
Next up: Fetch Errors — when requests fail