An HTTP client with fetch

fetch is the client side of the previous lesson: it takes a URL, sends a request and resolves with an answer object. The answer is not the body yet; it is the status, the headers and a promise of the body, which is why a program reads response.json() or response.text() after it has looked at the status.

Each program here starts the kind of server the previous lesson built, calls it with fetch and closes it, so the client code can be read without a second window. The lesson covers a plain request and its headers, the difference between a status and a failure, a JSON body and a POST that the server answers with 400. Every address is 127.0.0.1 with a port the system picked.

A request and its answer

The promise of fetch resolves as soon as the status line and the headers are in, and it rejects only when the request itself fails. The answer has status as a number, statusText as the phrase, a headers object and the body stream. headers.get reads a name without caring about case.

The server answers with a custom header and one line of text, and the client prints the status, the phrase, the type, the custom header and the body.

The file request.mjs:

import { createServer } from 'node:http'; const server = createServer((request, response) => { response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'X-Tool': 'js-course', }); response.end('the body of the answer\n'); }); await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve); }); const url = `http://127.0.0.1:${server.address().port}/hello`; const answer = await fetch(url); console.log('the status:', answer.status); console.log('the status text:', answer.statusText); console.log('the type:', answer.headers.get('content-type')); console.log('a custom header:', answer.headers.get('x-tool')); console.log('the body:', JSON.stringify(await answer.text())); await new Promise((resolve) => { server.close(resolve); });

node request.mjs

the status: 200
the status text: OK
the type: text/plain; charset=utf-8
a custom header: js-course
the body: "the body of the answer\n"

The body came back in quotes with a newline at the end, because the server sent one and the client does not trim it. The header names are lowercased by the answer object, which is what makes headers.get('x-tool') work for a name the server wrote in capitals.

Status codes and ok

A 404 is a successful exchange: the server answered, and the answer says the path does not exist. fetch resolves with it, and response.ok is the boolean that says whether the status is in the two hundreds. A program that wants to treat a 404 as a failure checks ok itself, which is one line and much clearer than a try around everything.

The program asks for an existing path and a missing one and prints the status and the flag for each, then reads the body of the missing one.

The file status.mjs:

import { createServer } from 'node:http'; const server = createServer((request, response) => { const found = request.url === '/ok'; response.writeHead(found ? 200 : 404, { 'Content-Type': 'text/plain' }); response.end(found ? 'here it is\n' : 'nothing here\n'); }); await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve); }); const base = `http://127.0.0.1:${server.address().port}`; for (const path of ['/ok', '/gone']) { const answer = await fetch(base + path); console.log(path, 'answered', answer.status, 'ok is', answer.ok); } const answer = await fetch(base + '/gone'); console.log('the body of the 404:', JSON.stringify(await answer.text())); await new Promise((resolve) => { server.close(resolve); });

node status.mjs

/ok answered 200 ok is true
/gone answered 404 ok is false
the body of the 404: "nothing here\n"

Nothing threw, and the two answers carried different statuses. The lesson on HTTP status codes groups them by the first digit, and the rule a client keeps is that ok covers 200 to 299 and every other status needs a decision of its own.

A JSON body

response.json() reads the body stream, parses it and returns a promise of the value, which is one line instead of two. The client should read the type first, because a server that answers with an HTML error page and a content type of JSON is a real failure mode and a parse error is a poor message for it. The lesson on JSON covers the format itself.

The server answers with an object that holds a name, a number and an array, and the client prints the type and three fields of the parsed body.

The file json.mjs:

import { createServer } from 'node:http'; const server = createServer((request, response) => { response.writeHead(200, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ name: 'notes', count: 2, items: ['a', 'b'] })); }); await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve); }); const url = `http://127.0.0.1:${server.address().port}/notes`; const answer = await fetch(url); const data = await answer.json(); console.log('the type:', answer.headers.get('content-type')); console.log('the name:', data.name); console.log('the count:', data.count); console.log('the items:', data.items.join(', ')); await new Promise((resolve) => { server.close(resolve); });

node json.mjs

the type: application/json
the name: notes
the count: 2
the items: a, b

The body became an object with an array in it, and the fields were read with dots. The count is a number and not a string because JSON has numbers, which is the difference from the environment variables of the lesson on process.

POST and a failure

A POST sends a body, and the body has to be a string, so a JSON body is JSON.stringify of the object plus a content type header that says so. The server in this program checks the field it needs and answers with 400 and a message when it is missing, which is the shape of every API that validates its input.

The program makes two requests to the same route, one with a title and one without, and prints the status and the JSON of each answer.

The file post.mjs:

import { createServer } from 'node:http'; const server = createServer(async (request, response) => { let body = ''; for await (const chunk of request) { body += chunk; } const data = body === '' ? {} : JSON.parse(body); if (typeof data.title !== 'string' || data.title === '') { response.writeHead(400, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ error: 'a title is required' })); return; } response.writeHead(201, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ id: 1, title: data.title })); }); await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve); }); const base = `http://127.0.0.1:${server.address().port}`; const created = await fetch(base + '/notes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'a note' }), }); console.log('a good request:', created.status, JSON.stringify(await created.json())); const bad = await fetch(base + '/notes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}), }); console.log('a bad request:', bad.status, JSON.stringify(await bad.json())); await new Promise((resolve) => { server.close(resolve); });

node post.mjs

a good request: 201 {"id":1,"title":"a note"}
a bad request: 400 {"error":"a title is required"}

The good request got 201 with the new note, and the bad one got 400 with the reason, and neither call threw. A client that ignores status would read the error object as if it were a note, which is why the check comes before the fields are touched.

Exercises

  1. Print every header of an answer with a for...of over answer.headers. What does each iteration give you?
  2. Ask for a path that does not exist and print only the status. Which line tells a failure from a success?
  3. Send a POST with an empty object and print the message of the server. Which status did it use?
  4. Make fetch reject without touching the network. Which kind of address does that?
  5. Add a header to the request and print it on the server side. Which object holds it there?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. When does fetch reject?

    Answer

    When the request itself fails, not on a 404

    An answer with a status is a successful exchange, whatever the status says.

  2. What does response.ok hold?

    Answer

    true when the status is between 200 and 299

    The flag is the shortcut for the range a successful answer lives in.

  3. What does this program print? ``import { createServer } from "node:http"; const server = createServer((request, response) => { response.writeHead(404, { "Content-Type": "text/plain" }); response.end("nothing"); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const answer = await fetch(http://127.0.0.1:${server.address().port}/); console.log(answer.status, answer.ok); await new Promise((resolve) => server.close(resolve));``

    Answer

    404 false

    The answer arrived with a status outside the successful range, and ok says so.

  4. What does response.json() return?

    Answer

    A promise of the parsed body

    It reads the stream, so the value has to be awaited.

  5. What does this program print? ``import { createServer } from "node:http"; const server = createServer((request, response) => { response.writeHead(200, { "Content-Type": "application/json" }); response.end(JSON.stringify({ count: 2 })); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const answer = await fetch(http://127.0.0.1:${server.address().port}/); const data = await answer.json(); console.log(data.count); await new Promise((resolve) => server.close(resolve));``

    Answer

    2

    JSON has a number type, so the field arrives as the number two.

  6. How is a JSON body sent with fetch?

    Answer

    body: JSON.stringify(value) and a content type header

    The body of a request is text, and the header says how to read it.

  7. What does this program print? console.log(JSON.stringify({ method: "POST", headers: { "Content-Type": "application/json" } }));

    Answer

    {"method":"POST","headers":{"Content-Type":"application/json"}}

    JSON.stringify writes the whole object, nested one included, on one line.

  8. What does statusText hold?

    Answer

    The standard phrase that belongs to the status

    It is the reason phrase of the status line, such as OK or Created.

  9. What does this program print? ``import { createServer } from "node:http"; const server = createServer((request, response) => { response.writeHead(200, { "Content-Type": "application/json" }); response.end("{}"); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const answer = await fetch(http://127.0.0.1:${server.address().port}/); console.log(answer.headers.get("content-type")); await new Promise((resolve) => server.close(resolve));``

    Answer

    application/json

    The header came with the answer, and the name is read in lowercase.

  10. Why does each program close the server before it ends?

    Answer

    An open server keeps the process alive

    The listening socket is pending work, so close is what lets the program end.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image