WeCodeAcademy

Node.js fetch and JSON

Node has fetch built in. This example talks to a small local server so it works without internet.

ExampleNode.js
const http = require("http");

const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ user: "Ada", repos: [{ name: "engine", stars: 12 }, { name: "notes", stars: 3 }] }));
});

server.listen(0, async () => {
  try {
    const res = await fetch(`http://localhost:${server.address().port}/`);
    console.log(res.ok, res.status, res.headers.get("content-type"));
    const data = await res.json();
    const stars = data.repos.reduce((sum, r) => sum + r.stars, 0);
    console.log(`${data.user} has ${stars} stars`);
  } finally {
    server.close();
  }
});
Output
true 200 application/json
Ada has 15 stars
Quick check

What does res.json() return?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.