fetch in the browser
A page asks a server for data with fetch and changes itself with the answer, and the call is the same one the lesson on an HTTP client built. What differs is the side the call comes from: a page has an origin, so a relative path is enough, and the answer is part of the page rather than a value in a variable of a program.
jsdom has no fetch of its own, so every program in this lesson hands the page the fetch of Node.js through a small wrapper that resolves a relative path against window.location. That wrapper is the only line a browser does not need. Each program starts a server on 127.0.0.1 with a port the system picks, as the server lesson showed, and closes it before the program ends. The page itself is opened with the two lines of the setup in the first lesson.
A page with a fetch of its own
The page gets the address of the server in its url option, so the origin of the page is the origin of the server; a relative path then means the same thing on both sides. window.fetch is a function the program assigns, and inside it the address of the page is the base of the new absolute address. In a browser the same call is written with the relative path and no wrapper, because the browser resolves it itself.
The program serves one JSON route, opens a page at the origin of the server, fetches the route and writes the answer into the page.
The file page.js:
const { createServer } = require('node:http');
const { JSDOM } = require('jsdom');
const server = createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ page: 'notes', path: request.url }));
});
async function main() {
await new Promise((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const origin = `http://127.0.0.1:${server.address().port}`;
const dom = new JSDOM('<!doctype html><title>Notes</title><p id="status">loading</p>', {
url: `${origin}/notes`,
});
const { window } = dom;
window.fetch = (path, options) => fetch(new URL(path, window.location.href), options);
const answer = await window.fetch('/api/notes');
const data = await answer.json();
console.log('the status:', answer.status, 'ok:', answer.ok);
console.log('the body:', JSON.stringify(data));
console.log('the page and the server share an origin:', new URL('/api/notes', window.location.href).origin === window.location.origin);
console.log('the page title:', window.document.title);
window.document.querySelector('#status').textContent = `${data.page} from ${data.path}`;
console.log('the page says:', window.document.querySelector('#status').textContent);
await new Promise((resolve) => {
server.close(resolve);
});
}
main();
node page.js
the status: 200 ok: true
the body: {"page":"notes","path":"/api/notes"}
the page and the server share an origin: true
the page title: Notes
the page says: notes from /api/notes
The answer arrived as an object and the page wrote a sentence from its fields, which is the loop of every page that loads data: a request, a parsed answer, and a text node that changes. The `http://127.0.0.1` address keeps the server on this machine, and the port came from the system, so two runs never collide.
Status codes on the page
A 404 is an answer and not a failure, so the promise resolves and the page has to decide what to show. answer.ok is true for a status between 200 and 299, and the HTTP status codes of the site group the rest. The body of a 404 often carries the reason, as the route below does, and a page that shows it is easier to debug than one that shows a blank panel.
The program asks for the route that exists and for one that does not, prints the status and the flag of each, reads the body of the missing one and takes a branch on the flag.
The file status.js:
const { createServer } = require('node:http');
const { JSDOM } = require('jsdom');
const server = createServer((request, response) => {
const found = request.url === '/api/notes';
response.writeHead(found ? 200 : 404, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(found ? { notes: ['first note'] } : { error: 'no such path' }));
});
async function main() {
await new Promise((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const origin = `http://127.0.0.1:${server.address().port}`;
const dom = new JSDOM('<!doctype html><title>Notes</title>', { url: `${origin}/notes` });
const { window } = dom;
window.fetch = (path, options) => fetch(new URL(path, window.location.href), options);
for (const path of ['/api/notes', '/api/missing']) {
const answer = await window.fetch(path);
console.log(path, 'answered', answer.status, 'ok is', answer.ok);
}
const missing = await window.fetch('/api/missing');
console.log('the body of the 404:', JSON.stringify(await missing.json()));
const answer = await window.fetch('/api/missing');
if (answer.ok) {
console.log('the page shows the notes');
} else {
console.log('the page shows an error, status', answer.status);
}
await new Promise((resolve) => {
server.close(resolve);
});
}
main();
node status.js
/api/notes answered 200 ok is true
/api/missing answered 404 ok is false
the body of the 404: {"error":"no such path"}
the page shows an error, status 404
Nothing was thrown, and the branch on ok is the whole difference between a page that shows the notes and one that shows an error. A program that reads the fields of the answer before looking at the flag reads the error object as if it were a list, which is the bug this lesson is written to avoid.
A POST from the page
A send is a request with a method, a content type and a body, and the body of a JSON send is JSON.stringify of the object. The server in the program checks the field it needs and answers 201 when it saved the note and 400 with a reason when the title is empty, which is the shape of every API that validates its input. The page reads both answers and prints the status and the body of each.
The program sends a note with a title and a note without one, from a page at the origin of the server, and closes the server at the end.
The file post.js:
const { createServer } = require('node:http');
const { JSDOM } = require('jsdom');
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 }));
});
async function main() {
await new Promise((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const origin = `http://127.0.0.1:${server.address().port}`;
const dom = new JSDOM('<!doctype html><title>Notes</title>', { url: `${origin}/notes/new` });
const { window } = dom;
window.fetch = (path, options) => fetch(new URL(path, window.location.href), options);
async function save(title) {
const answer = await window.fetch('/api/notes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(title === '' ? {} : { title }),
});
return { status: answer.status, body: await answer.json() };
}
const good = await save('a note from the page');
console.log('a good save:', good.status, JSON.stringify(good.body));
const bad = await save('');
console.log('an empty title:', bad.status, JSON.stringify(bad.body));
await new Promise((resolve) => {
server.close(resolve);
});
}
main();
node post.js
a good save: 201 {"id":1,"title":"a note from the page"}
an empty title: 400 {"error":"a title is required"}
The page sent one body with a title and one with an empty object, and the server answered with a new note and with a reason. The status is what a page branches on, and the message in the body is what it shows to the reader, which is why an API writes a sentence in the error object rather than a code alone.
When the request fails
A request that never reaches a server rejects the promise, and the error is a TypeError with the message fetch failed whatever the cause: a closed port, a name that does not resolve, a connection that broke. The cause is on the cause property, and its code is the one worth matching, such as ECONNREFUSED. A page shows a sentence about the network to the reader and keeps the code for the console.
The program calls the server once, closes it, calls it again and prints what the failure carries.
The file failure.js:
const { createServer } = require('node:http');
const { JSDOM } = require('jsdom');
const server = createServer((request, response) => {
response.end('still here\n');
});
async function main() {
await new Promise((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const origin = `http://127.0.0.1:${server.address().port}`;
const dom = new JSDOM('<!doctype html><title>Notes</title>', { url: `${origin}/notes` });
const { window } = dom;
window.fetch = (path, options) => fetch(new URL(path, window.location.href), options);
const first = await window.fetch('/api/notes');
console.log('before the close:', first.status);
await new Promise((resolve) => {
server.close(resolve);
});
try {
await window.fetch('/api/notes');
} catch (error) {
console.log('the name:', error.name);
console.log('the message:', JSON.stringify(error.message));
console.log('the cause:', error.cause.code);
}
console.log('no answer was made, so ok was never read');
}
main();
node failure.js
before the close: 200
the name: TypeError
the message: "fetch failed"
the cause: ECONNREFUSED
no answer was made, so ok was never read
The first call had a server and the second had none, so the error arrived before any status existed. That is the border of the two failure kinds: a status is a decision the page makes, and a rejection is something the page can only report. A catch that reads error.cause.code keeps the detail for the console and a sentence for the reader.
Exercises
- Print every header of an answer with for...of over answer.headers. What does each iteration give?
- Remove the wrapper and call window.fetch('/api/notes') directly. Which error comes back, and why does a browser not have it?
- Answer the route with 500 and print the status in the page. Which branch of the program runs?
- Send a POST with a content type of text but a JSON body. What does the server see, and which status should it answer?
- Ask for a route on a port nobody listens on, such as 9. Which code does the cause carry on this machine?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where does the fetch of the page come from in these programs?
Answer
The program gives the page the fetch of Node.js
jsdom has no fetch, so the program assigns one, and a browser would already have it.
-
What does this program print?
const { createServer } = require("node:http"); const { JSDOM } = require("jsdom"); const server = createServer((request, response) => { response.writeHead(404, { "Content-Type": "text/plain" }); response.end("nothing here"); }); async function main() { await new Promise((resolve) => { server.listen(0, "127.0.0.1", resolve); }); const origin = "http://127.0.0.1:" + server.address().port; const dom = new JSDOM("<p>a page</p>", { url: origin + "/notes" }); dom.window.fetch = (path, options) => fetch(new URL(path, dom.window.location.href), options); const answer = await dom.window.fetch("/api/missing"); console.log(answer.status, answer.ok); await new Promise((resolve) => { server.close(resolve); }); } main();Answer
404 false
The exchange succeeded and the answer carries a status outside the successful range.
-
When does fetch reject?
Answer
When the request itself fails, not on a 404
An answer with any status is a successful exchange, so the page decides what the status means.
-
What does this program print?
const { createServer } = require("node:http"); const { JSDOM } = require("jsdom"); const server = createServer((request, response) => { response.end("still here"); }); async function main() { await new Promise((resolve) => { server.listen(0, "127.0.0.1", resolve); }); const origin = "http://127.0.0.1:" + server.address().port; const dom = new JSDOM("<p>a page</p>", { url: origin + "/notes" }); dom.window.fetch = (path, options) => fetch(new URL(path, dom.window.location.href), options); await new Promise((resolve) => { server.close(resolve); }); try { await dom.window.fetch("/api/notes"); } catch (error) { console.log(error.message); } } main();Answer
fetch failed
The port is closed, so the request fails and the message is the general one; the code lives on the cause.
-
Why does the wrapper build a URL with new URL before calling fetch?
Answer
The fetch of Node.js needs an absolute address
A browser resolves a relative path against the page, and Node.js has no page to resolve it against.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>a page</p>", { url: "http://127.0.0.1:8080/notes" }); dom.window.fetch = (path, options) => fetch(new URL(path, dom.window.location.href), options); console.log(new URL("/api/notes", dom.window.location.href).pathname);Answer
/api/notes
A path that starts with a slash replaces the whole path of the base address.
-
What does response.json() return?
Answer
A promise of the parsed body
It reads the body stream, so the value has to be awaited before a field can be read.
-
What does this program print?
const body = JSON.stringify({ title: "a note" }); console.log(body, typeof body);Answer
{"title":"a note"} string
A request body is text, and stringify is what turns the object into that text.
-
Which status fits a request that came without the required title?
Answer
400, because the request is wrong
The server understood the request and refused it as malformed, which is the four hundreds.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>a page</p>", { url: "http://127.0.0.1:8080/notes" }); console.log(new URL("/api/notes", dom.window.location.href).href);Answer
http://127.0.0.1:8080/api/notes
The answer is the absolute address the fetch of Node.js receives from the wrapper.
The programs on this page were run with Node.js 24.22.1 against jsdom 30.1.3 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container. Every server listened on 127.0.0.1 with a port the system picked.
Article author: Arthur Isaev