T5 Modern JavaScript (ES6 and later) · Lesson 9
fetch
Asking a server for data from JavaScript: fetch and the Response it gives, the status that must be read before the body is believed, sending JSON with POST, building addresses with URL and URLSearchParams, cancelling and time limits with AbortController, and why a browser blocks answers from another origin.
- fetch data from a server, and read a Response's status, headers and JSON body
- tell an error status from a failed request, and turn both into errors you can catch
- send JSON to a server with POST, with the right method, header and body
- build addresses safely with URL and URLSearchParams
- cancel a request and set a time limit with AbortController and AbortSignal.timeout
- say what an origin is, why CORS blocks an answer, and who can fix it
The back cover
Most pages show data that lives somewhere else: prices in a shop's database, trains in a railway's timetable, the weather in a forecaster's computer. The function fetch asks a server for such data from JavaScript, and the page shows it without reloading.
These pages show how fetch asks, and the Response it gives. They show why the status must be read before the body is believed, and how to send JSON with POST. They show addresses built safely with URL, time limits and cancelling, and the rules that decide which other sites a page may read.
Before you start
The story: The day the clocks read NaN
Every morning the upper floor asks the Observatory across the river for the exact time, over the city's wires, and sets its clocks by the answer. This morning a clerk at the Observatory had moved the file. The wire brought back a polite note that said it could not be found. The script never read the note. It took the note for the time.
Every clock on the floor now shows NaN:NaN, and the market is asking why.
Master Hakim Verge taps the dead faces one by one. "The wire worked," he says. "A wire that carries bad news has not failed. It has done its job. Your job is to read the answer before you believe it."
Most of what a modern page shows is not in its HTML. A shop's prices, a school's results and a bank's balance all come from a server after the page has loaded, and a script asks for them. The tool for asking is fetch. This lesson uses everything from the last three lessons, on a real server at last, in place of the wait helper.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Requests and responses. | The browser asks; the server answers. | fetch makes a request from a script. |
| Status codes. | 200, 404, 500 | The first thing to read in an answer. |
| Headers. | content-type: application/json | Reading and sending them. |
| JSON. | JSON.parse and JSON.stringify | The usual form of data on the wire. |
| await and try. | try { await job(); } catch (err) { ... } | Every request can fail. |
| Error classes. | class HttpError extends Error | A failure that carries its status. |
| Promise.all. | await Promise.all([a, b]) | Several requests at once. |
| Top-level await. | <script type="module"> | The pages in this lesson use it. |
| textContent. | el.textContent = "₹60"; | Putting fetched data on the page. |
| The Network panel. | One row for each request. | Each fetch appears there. |
By the end of this lesson you will be able to:
- fetch data from a server, and read a Response's status, headers and JSON body;
- tell an error status from a failed request, and turn both into errors you can catch;
- send JSON to a server with POST, with the right method, header and body;
- build addresses safely with URL and URLSearchParams;
- cancel a request and set a time limit with AbortController and AbortSignal.timeout;
- say what an origin is, why CORS blocks an answer, and who can fix it.
How to follow this lesson
A request needs a server, so the fetch blocks were run by the kit on a small real server, in Chrome, and the notes under each block show what Chrome did. Open the Network panel on any real site as you read: every row with the type fetch is a script doing what this lesson teaches.
In one line
fetch asks a server for data from a script; the lesson is mostly about reading the answer carefully, as a working wire can still bring bad news.
Asking a server
At a glance
A courier service hands over a receipt when the parcel is accepted, and the parcel itself arrives later. Asking a server for data works in the same two steps.
The call fetch(url) gives a promise of a Response as soon as the headers arrive. Then res.json() or res.text() gives a second promise, for the body, which can be read only once. A Response also holds the status, the ok flag and the headers, which can be checked before the body is read.
Take a guess: What was the name, coined in 2005, for pages that fetch data without reloading?
A built-in function that asks a server for something. fetch("stock.json") starts the request at once, and gives a promise of a Response, the object that holds the server's answer.
Here is a page that asks for a small file of JSON, read in a module so that await can stand at the top level:
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = await fetch("stock.json");
const data = await res.json();
console.log(data.rice, data.dal);
</script>
The Network panel shows
200 document /
200 fetch /stock.json
The Console shows
Info 12 7
Two awaits, for two stages. The first ends when the status and the headers have arrived, which is enough to give you a Response. The body may still be on its way, so reading it is a second promise: res.json() waits for the whole body, parses it as JSON, and gives the result.
What a Response holds
A Response can be made by hand, which lets you try one on this page with no server at all. It is the same class that fetch gives you:
const res = new Response('{ "rice": 12 }', {
status: 200,
headers: { "Content-Type": "application/json" },
});
console.log(res.status, res.ok, res.headers.get("content-type"));
const data = await res.json();
console.log(data.rice);
200 true application/json
12
| Read | Gives | Example |
|---|---|---|
res.status | the status code | 200 |
res.ok | true for a status from 200 to 299 | true |
res.headers.get("content-type") | one header, with any capitals | application/json |
await res.json() | the body, parsed as JSON | { rice: 12 } |
await res.text() | the body as plain text | the same, unparsed |
A body can be read once
The body arrives as a stream, and reading it uses it up. A second read is an error, so keep what the first read gave you in a const:
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = await fetch("stock.json");
console.log((await res.json()).rice);
console.log(await res.text());
</script>
The Console shows
Info 12
Error Uncaught TypeError: Failed to execute 'text' on 'Response': body stream already read
Worked example 1
The canteen's page shows today's dishes, which live in menu.json on the server. Fetch them, and write each one with its price into the page's list.
What we have: a page with an empty paragraph, and a JSON file of dishes
What we need: the dishes shown on the page
The plan: fetch the file, read its JSON, map each dish to a line of text, and put the result in with textContent
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<p id="menu">Loading...</p>
<script type="module">
const res = await fetch("menu.json");
const dishes = await res.json();
const line = dishes.map((d) => `${d.name} ₹${d.price}`).join(", ");
document.getElementById("menu").textContent = line;
console.log(document.getElementById("menu").textContent);
</script>
The Console shows
Info Thali ₹120, Poha ₹40
The page shows Thali ₹120, Poha ₹40.
Check: the paragraph's text was read back from the page after it was set.
A path that fails: forgetting the second await: const dishes = res.json();. dishes is then a promise, and dishes.map is not a function.
When you are stuck: fetch gives you something you did not expect
A Response where you wanted data? Read the body: await res.json().
A promise where you wanted data? One of the two awaits is missing.
body stream already read? Keep the first read in a const.
Open the Network panel: the request's row shows what the server really sent.
Your turn
const res = new Response("hello", { status: 201 });
console.log(res.ok, res.status, await res.text());
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
true 201 hello
- 201 is between 200 and 299, so ok is true.
- text() gives the body.
It prints true 201 hello.
Why does reading JSON from fetch need two awaits?Tap to reveal
- The first promise is fulfilled when the headers arrive.
- The body may still be coming, so reading it is a second promise.
Because the headers and the body arrive at different times.
How do you read the content-type of a Response?Tap to reveal
- Headers are read with get.
res.headers.get("content-type")
Did you know?
Ajax, named in 2005
Asking a server for data without reloading the page once had a famous name. On 18 February 2005 Jesse James Garrett used the term Ajax in an article titled Ajax: A New Approach to Web Applications. The essay calls the name shorthand for Asynchronous JavaScript + XML, and a fundamental shift in what is possible on the web. fetch is today's way to do that job.
Why it fits here: It answers this topic's question, and places fetch in history: pages that load data without reloading were named Ajax in 2005.
Sources: Wikipedia: Ajax (programming); Jesse James Garrett: Ajax: A New Approach to Web Applications
fetch reaches Node.js
Node.js has fetch too. Its documentation calls it a browser-compatible implementation of the fetch() function, added in version 17.5.0. From version 18.0.0 it no longer needed the --experimental-fetch flag, and from version 21.0.0 it was no longer marked experimental. So the same fetch code can run in a browser and on a server.
Why it fits here: It widens this topic's fetch: the same function now works in Node.js programs, not only in browsers.
Source: Node.js documentation: Globals
In one line
fetch(url) gives a promise of a Response once the headers arrive; res.json() or res.text() gives a second promise of the body, which can be read only once. A Response holds status, ok and headers.
Reading the answer before you believe it
At a glance
A shop that answers the phone to say it is closed has still answered. The call worked; the news is bad. A server's reply works the same way.
fetch rejects only when no answer arrives at all. A 404 or a 500 is an answer, with ok set to false, so read res.ok before believing the body. Turn a bad status into an error of your own, in one helper that every request uses, and the rest of the code can trust what it gets.
Take a guess: Which status numbers make res.ok true?
Here is the upper floor's morning request, on the morning the clerk moved the file. The server answered, so as far as fetch is concerned, all went well:
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = await fetch("time.json");
console.log(res.status, res.ok);
</script>
The Network panel shows
200 document /
404 fetch /time.json
The Console shows
Error Failed to load resource: the server responded with a status of 404 (Not Found)
Info 404 false
Read that carefully: fetch did not fail. A status of 404 is an answer, so the promise was fulfilled, and the code went on to the next line. The red line in the Console comes from the browser, not from your code. Only res.ok tells your code that something is wrong. A server that breaks gives the same result, with a 500:
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = await fetch("time.json");
console.log(res.status, res.ok);
</script>
The Console shows
Error Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Info 500 false
Code that skips the check believes whatever came back. The kit's server writes Not found in the body of a 404, and JSON cannot read that:
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = await fetch("time.json");
const time = await res.json();
console.log(time.hour);
</script>
The Console shows
Error Failed to load resource: the server responded with a status of 404 (Not Found)
Error Uncaught SyntaxError: Unexpected token 'N', "Not found" is not valid JSON
The message blames the JSON, and the real cause is one line higher: nobody read the status.
When there is no answer at all
fetch rejects only when no answer arrives: the server is down, the network has gone, the address does not exist. Here the script asks a port where nothing is listening:
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
try {
await fetch("http://127.0.0.1:65500/time.json");
} catch (err) {
console.log(err.name, err.message);
}
</script>
The Console shows
Error Failed to load resource: net::ERR_CONNECTION_REFUSED
Info TypeError Failed to fetch
| What happened | fetch's promise | How your code knows |
|---|---|---|
| 200, with good JSON | fulfilled | res.ok is true |
| 404, 500 or any error status | fulfilled | res.ok is false |
| no answer at all | rejected | a TypeError at the await |
| an answer that is not JSON | fulfilled; res.json() is rejected | a SyntaxError at the second await |
One helper for every request
Every request needs the same check, so write it once. getJson turns a bad status into an error, so that the code around it has only one way to fail:
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
async function getJson(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`${url} answered ${res.status}`);
return res.json();
}
try {
const stock = await getJson("stock.json");
console.log(stock.rice);
await getJson("time.json");
} catch (err) {
console.log(err.message);
}
</script>
The Console shows
Info 12
Error Failed to load resource: the server responded with a status of 404 (Not Found)
Info time.json answered 404
Worked example 2
The clocks must be set from time.json each morning. When the request fails in any way, they must keep yesterday's time and write the reason in the log. An error class should carry the status, so that a 404 can be told from a 500.
What we have: a request that can fail three ways
What we need: the clocks set, or yesterday's time kept, with the reason logged
The plan: an HttpError class with a status; getJson throws it for a bad status; one try and catch around the morning's work
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
class HttpError extends Error {
constructor(url, status) {
super(`${url} answered ${status}`);
this.name = "HttpError";
this.status = status;
}
}
async function getJson(url) {
const res = await fetch(url);
if (!res.ok) throw new HttpError(url, res.status);
return res.json();
}
let hour = 11;
try {
const time = await getJson("time.json");
hour = time.hour;
} catch (err) {
console.log(`keeping ${hour}.00:`, err.name, err.status ?? "", err.message);
}
</script>
The Console shows
Error Failed to load resource: the server responded with a status of 404 (Not Found)
Info keeping 11.00: HttpError 404 time.json answered 404
The clocks keep 11.00, and the log says time.json answered 404.
Check: hour was changed only after a good answer, so a failure left it alone.
A path that fails: setting the clocks straight from time.hour with no check. That is the NaN:NaN of the scene: every step worked, and the clocks showed nonsense.
When you are stuck: a request seems to work and the data is wrong
Read res.status and res.ok first; a 404 does not reject.
Unexpected token in JSON usually means the answer was an error page: look at res.status, or at the body with res.text().
Failed to fetch means no answer arrived: the address, the server, the network, or CORS.
The red Console line for a 404 is the browser's: your code still has to check.
Your turn
const res = new Response("Not found", { status: 404 });
console.log(res.ok);
try {
await res.json();
} catch (err) {
console.log(err.name);
}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
false
SyntaxError
- 404 is not between 200 and 299.
- The body is not JSON, so reading it as JSON fails.
It prints false, then SyntaxError.
Does a 500 answer reject fetch's promise?Tap to reveal
- The server answered.
- fetch rejects only when no answer arrives.
No: it is fulfilled, with ok false.
What is the first thing to read in every answer?Tap to reveal
- The status decides whether the body can be believed.
res.ok, or res.status.
Did you know?
What counts as ok
The ok flag has an exact meaning. The Fetch standard defines an ok status as a status in the range 200 to 299, inclusive, and MDN describes ok as stating whether the response was successful. So a 404 or a 500 gives ok as false, while 200, 201 and 204 all give true. Anything outside that one range fails the check.
Why it fits here: It answers this topic's question: res.ok is true exactly for statuses 200 to 299.
Sources: WHATWG: Fetch Standard; MDN: Response.ok
Reading a body twice
A body can be read only once, but a copy can be made first. MDN explains that clone() makes a copy of a response, identical in every way, and that the main reason clone() exists is to allow several uses of a body that can be read only once. The Fetch standard's steps throw a TypeError if clone() is called when the body can no longer be used.
Why it fits here: It gives a way round this topic's read-once rule: clone the response first, then read each copy once.
Sources: MDN: Response.clone(); WHATWG: Fetch Standard
In one line
fetch rejects only when no answer arrives. A 404 or a 500 is an answer, with ok false, so read res.ok before the body, and turn a bad status into an error of your own, in one helper.
Sending data to a server
At a glance
A letter needs an envelope that says what kind of post it is, and the letter itself inside. Sending data to a server needs the same parts.
The call fetch(url, options) sends data. The method says what kind of request it is, the headers describe it, and the body carries it as text, so an object goes through JSON.stringify first. A Content-Type header of application/json tells the server what the text is. Then read the status of the answer, as with any request.
Take a guess: Can fetch send a body with a GET request?
So far every request has asked for something. A request can also carry something: an order, a form, a new password. A second argument to fetch, an options object as in lesson 03, says how.
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const order = { item: "dosa", qty: 2 };
const res = await fetch("/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(order),
});
const got = await res.json();
console.log(res.status, got.method, got.type);
console.log(got.body);
</script>
The Network panel shows
200 document /
201 fetch /orders
The Console shows
Info 201 POST application/json
Info {"item":"dosa","qty":2}
The kit's small server has a path that answers with what it received, so this block shows the far end of the wire. Three things were sent, and each has its own job.
- method says what kind of request this is. POST means: take this and do something with it. With no method, fetch uses GET.
- headers describe the request. Content-Type tells the server how to read the body.
- body is the data itself, here as text. An object must be turned into JSON text first, with JSON.stringify.
The server answered 201, Created, a status that means the new thing now exists. It is between 200 and 299, so res.ok is true.
Forget the JSON.stringify
A plain object is not something a body can carry. Given one, fetch turns it into text the way a gap in a template does, and the server receives the words from lesson 02:
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = await fetch("/orders", { method: "POST", body: { item: "dosa" } });
const got = await res.json();
console.log(got.type, "|", got.body);
</script>
The Console shows
Info text/plain;charset=UTF-8 | [object Object]
Nothing failed on your side. The order was lost at the other end, and the type says text/plain, because no header said otherwise. A real server would answer with an error, or quietly store nonsense.
| Method | Means | Example |
|---|---|---|
| GET | give me this; it changes nothing | read the menu |
| POST | take this: make something new | place an order |
| PUT | replace this with what I send | save a whole profile |
| PATCH | change part of this | change only the phone number |
| DELETE | remove this | cancel an order |
The APIs step goes through these methods and statuses in depth. For now, the shape of the call is the same for all of them.
Worked example 3
A cinema's page books a seat with a POST to /book. A seat that is already taken is answered with 409, Conflict. Write book(seat), which gives booked for a good answer, and a clear message for a 409.
What we have: a seat number, and a server that may refuse it
What we need: a message for each outcome
The plan: POST the seat as JSON, read res.status, and treat 409 as a normal outcome, not a crash
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
async function book(seat) {
const res = await fetch("/book", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ seat }),
});
if (res.status === 409) return `Seat ${seat} is taken`;
if (!res.ok) throw new Error(`Booking answered ${res.status}`);
return "booked";
}
console.log(await book(42));
</script>
The Console shows
Error Failed to load resource: the server responded with a status of 409 (Conflict)
Info Seat 42 is taken
The page says Seat 42 is taken.
Check: the server's 409 was an answer the code expected, so nothing was thrown.
A path that fails: checking only res.ok. A taken seat and a broken server would then give the same message, and the customer would never learn to pick another seat.
When you are stuck: the server does not understand what you sent
Look at the request in the Network panel: its Payload tab shows the body as it was sent.
[object Object] in the body means JSON.stringify is missing.
An error such as 415 or 400 often means the Content-Type header is missing or wrong.
Check the method: fetch uses GET unless told otherwise, and a GET cannot have a body.
Your turn
What does fetch use when the options name no method?Tap to reveal
- Reading is the most common request.
GET.
Write the options for sending { name: "Asha" } as JSON with POST.Tap to reveal
- A method, a Content-Type header, and a stringified body.
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Asha" }) }
A server answers 201. Is res.ok true?Tap to reveal
- ok is true from 200 to 299.
Yes.
Did you know?
JSON that arrives as plain text
A body sent as a string gets a type of its own. The Fetch standard's steps say that when the body is a string, its type is set to text/plain;charset=UTF-8. So JSON sent without a Content-Type header reaches the server labelled as plain text, and a server that reads only JSON may ignore it. That is why the header is set to application/json.
Why it fits here: It explains this topic's Content-Type header: without it, a JSON string is sent labelled as plain text.
Source: WHATWG: Fetch Standard
A GET with a body is refused
fetch refuses one combination outright. The Fetch standard's steps say that if a body is given and the method is GET or HEAD, fetch must throw a TypeError. Data for a GET travels in the address instead, as search parameters, which the next topic builds safely with URL.
Why it fits here: It answers this topic's question, and explains why data is sent with POST: fetch will not send a body with GET at all.
Source: WHATWG: Fetch Standard
In one line
fetch(url, options) sends data: method says what kind of request, headers describe it, and body carries it as text, so objects go through JSON.stringify. Read the status of the answer as usual.
Building addresses safely
At a glance
An address written by hand can be misread if a word runs into the next. A web address is stricter still: some characters would break it unless they are written in a special way.
Read and build addresses with URL and its searchParams, never by pasting typed text into a template. searchParams.set escapes whatever would break the address, such as a space or an ampersand, and get gives the text back exactly. The URL object also splits an address into its parts, such as the host and the path.
Take a guess: In a query string, what does a plus sign mean?
Requests often carry their details in the address itself, after a question mark: what to search for, which page, how many. It is tempting to build such an address with a template literal. It works, until somebody searches for something with an ampersand in it.
A built-in class that reads an address into its parts: new URL(address). Its property searchParams holds the part after the question mark, called the query string, as name and value pairs.
const url = new URL("https://shop.example/search?q=tea&page=2");
console.log(url.host, url.pathname, url.search);
console.log(url.searchParams.get("q"), url.searchParams.get("page"));
shop.example /search ?q=tea&page=2
tea 2
Text that breaks an address
In a query string, & separates the pairs. So a search for tea & snacks, pasted in with a gap, is read as q=tea, followed by a second pair called snacks with no value:
const text = "tea & snacks";
const bad = new URL(`https://shop.example/search?q=${text}`);
console.log(JSON.stringify(bad.searchParams.get("q")));
console.log(bad.href);
"tea "
https://shop.example/search?q=tea%20&%20snacks
The server would search for the word tea and a space. Nothing fails, and the customer gets the wrong results. It is the same mistake as putting a name into HTML without escaping it, in the template literals lesson, and it has the same cure: let a tool that knows the rules do the escaping.
const url = new URL("https://shop.example/search");
url.searchParams.set("q", "tea & snacks");
url.searchParams.set("page", 2);
console.log(url.href);
console.log(url.searchParams.get("q"));
https://shop.example/search?q=tea+%26+snacks&page=2
tea & snacks
searchParams wrote the & as %26 and each space as +, and reads them back as they were typed. A URL object can be handed straight to fetch, as fetch(url).
Other useful forms
With a second argument, URL works out a relative address, as a browser does for a link. URLSearchParams can also be used alone, and made from an object:
console.log(new URL("../img/tea.png", "https://shop.example/menu/today/").href);
console.log(new URLSearchParams({ q: "dal", page: 1 }).toString());
https://shop.example/menu/img/tea.png
q=dal&page=1
| Part | Read with | In https://shop.example/search?q=tea |
|---|---|---|
| the host | url.host | shop.example |
| the path | url.pathname | /search |
| the query string | url.search | ?q=tea |
| one value | url.searchParams.get("q") | tea |
| the whole address | url.href | the whole address, escaped |
Worked example 4
A shop's search page must build an address from whatever the customer typed, and a page number, for the path /search on its own site. Write searchUrl(text, page), and try it with text that has an ampersand and with Hindi.
What we have: typed text and a page number
What we need: an address that keeps the text exactly
The plan: make a URL for the path, set q and page with searchParams, and read href
function searchUrl(text, page) {
const url = new URL("/search", "https://shop.example");
url.searchParams.set("q", text);
url.searchParams.set("page", page);
return url;
}
console.log(searchUrl("rice & dal", 1).href);
console.log(searchUrl("चाय", 2).searchParams.get("q"));
https://shop.example/search?q=rice+%26+dal&page=1
चाय
The ampersand is written %26, and चाय comes back as typed.
Check: get gives back exactly the text that set was given.
A path that fails: building it with a gap: `/search?q=${text}&page=${page}`. The customer who types rice & dal gets the results for rice.
When you are stuck: a query string goes wrong
Print url.href, and read what is really being asked for.
Never put typed text into an address with a gap: use searchParams.set.
new URL with a relative address needs a base as its second argument, or it throws a TypeError.
In the Network panel, the request's Payload tab shows the query string, read into pairs.
Your turn
const url = new URL("https://a.example/s");
url.searchParams.set("name", "Asha K");
console.log(url.search);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
?name=Asha+K
- set adds the pair.
- A space is written as a plus sign.
It prints ?name=Asha+K.
Why is `?q=${text}` unsafe for typed text?Tap to reveal
- The text may hold &, = or #, which have jobs in an address.
Because such characters break the address; searchParams escapes them.
How do you read the value of page from a URL object?Tap to reveal
- searchParams has get.
url.searchParams.get("page")
Did you know?
One standard for addresses
Browsers once disagreed about addresses. The WHATWG's URL Standard notes that spaces, other illegal characters, query encoding and equality were concepts not entirely shared, or defined. It sets out to align RFC 3986 and RFC 3987, the older standards for addresses, with what browsers really do, and to obsolete those RFCs in the process. The URL object follows that standard.
Why it fits here: It explains why this topic builds addresses with URL: it follows one standard that browsers now share.
Source: WHATWG: URL Standard
Plus means space
In a query string, a plus sign means a space. MDN warns that the URLSearchParams constructor interprets plus signs as spaces, which might cause problems, and the URL standard's steps say so plainly: replace any + in a name and value with a space. So a value such as +91 must be escaped, as searchParams.set does, or its + is lost.
Why it fits here: It answers this topic's question: in a query string + stands for a space, so set must escape a real plus sign.
Sources: MDN: URLSearchParams; WHATWG: URL Standard
In one line
Read and build addresses with URL and its searchParams, never by pasting typed text into a template: searchParams.set escapes what would break the address, and get gives it back exactly.
Time limits and cancelling
At a glance
A shopper who changes their mind tells the shopkeeper to stop packing the first order. Code can tell fetch to stop in the same way.
Give fetch a signal. AbortSignal.timeout(ms) sets a time limit, and an AbortController cancels by hand. When a new request starts, cancel the old one, or a late answer can arrive after a newer one and overwrite it on the page. That mistake, where the order of finishing decides the result, is called a race condition.
Take a guess: Why does fetch need a separate signal to cancel, instead of a cancel method on its promise?
A fetch with no limit can wait for a very long time on a server that has stopped answering, with a spinner turning all the while. Your code should decide how long it is willing to wait. The tool is an abort signal, an object handed to fetch that can call the request off.
A function that makes a signal which fires by itself after a number of milliseconds. fetch(url, { signal: AbortSignal.timeout(5000) }) gives up after five seconds, and rejects with an error named TimeoutError.
On a real site, where slow.json takes 1 second
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
try {
const res = await fetch("slow.json", { signal: AbortSignal.timeout(100) });
console.log(await res.text());
} catch (err) {
console.log(err.name, "|", err.message);
}
</script>
The Console shows
Info TimeoutError | signal timed out
After 100 milliseconds the request was called off, and the await threw. Unlike a race against a timer, in the promises lesson, this really stops the request, instead of only ceasing to wait for it.
Cancelling by hand
To cancel for your own reasons, such as a customer pressing Stop, make an AbortController. Its signal goes to fetch, and calling its abort() method cancels the request:
On a real site, where slow.json takes 1 second
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const controller = new AbortController();
const request = fetch("slow.json", { signal: controller.signal });
controller.abort();
try {
await request;
} catch (err) {
console.log(err.name, "|", err.message);
}
</script>
The Console shows
Info AbortError | signal is aborted without reason
The answer that arrives too late
A search box asks the server each time a letter is typed. The answer for te may be slower than the answer for tea, which was asked for later. Then the old answer lands last, and the page shows results for what the customer typed before:
On a real site, where te.json takes 300 ms
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
async function search(word) {
const res = await fetch(`${word}.json`);
console.log("show", (await res.json()).word);
}
search("te");
search("tea");
</script>
The Console shows
Info show tea
Info show te
This is called a race condition: the result depends on which of two things finishes first. The cure is to cancel the old request when a new one starts:
On a real site, where te.json takes 300 ms
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
let current;
async function search(word) {
current?.abort();
current = new AbortController();
try {
const res = await fetch(`${word}.json`, { signal: current.signal });
console.log("show", (await res.json()).word);
} catch (err) {
if (err.name !== "AbortError") throw err;
console.log("dropped", word);
}
}
search("te");
search("tea");
</script>
The Console shows
Info dropped te
Info show tea
Each search cancels the one before it, with current?.abort(), and the optional chaining skips that on the first search, when there is nothing to cancel. A cancelled search is expected, so the catch ignores AbortError and throws anything else on.
| Tool | Use | Error name |
|---|---|---|
AbortSignal.timeout(ms) | a time limit | TimeoutError |
new AbortController() | cancelling by hand | AbortError |
controller.signal | handed to fetch as signal | |
controller.abort() | calls the request off |
Worked example 5
The upper floor's morning request should wait 5 seconds for the Observatory, and keep yesterday's time after that. In a test, the limit is 100 milliseconds, and the Observatory takes a second. Write it, naming the reason in the log.
What we have: a slow server, and a limit
What we need: yesterday's time kept, and the reason logged
The plan: pass AbortSignal.timeout to fetch inside a try, and tell a timeout from other failures by the error's name
On a real site, where time.json takes 1 second
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
let hour = 11;
try {
const res = await fetch("time.json", { signal: AbortSignal.timeout(100) });
hour = (await res.json()).hour;
} catch (err) {
const why = err.name === "TimeoutError" ? "no answer in time" : err.message;
console.log(`keeping ${hour}.00: ${why}`);
}
</script>
The Console shows
Info keeping 11.00: no answer in time
The clocks keep 11.00, and the log says no answer in time.
Check: the request never finished, so hour was never changed.
A path that fails: no limit at all. The clocks then wait on the Observatory for as long as the browser allows, and the morning's work never reaches its next line.
When you are stuck: a request waits too long, or an old answer wins
Give every request a limit with AbortSignal.timeout.
An old answer on the page means a race: cancel the old request when a new one starts.
A cancelled request rejects: catch AbortError and ignore it.
A signal can be used once: make a new AbortController for each request.
Your turn
What is the error's name when AbortSignal.timeout fires?Tap to reveal
- A time limit has its own error name.
TimeoutError.
Why does a race against a timer not stop a request, while a signal does?Tap to reveal
- Promise.race only stops waiting.
- A signal tells fetch to call the request off.
Because race ignores the request; the signal cancels it.
Why does the search box cancel the old request?Tap to reveal
- An old answer can arrive after a new one.
So that a late answer cannot overwrite a newer one.
Did you know?
Promises that cannot be cancelled
A promise cannot be cancelled. TC39 once had a proposal for cancelable promises, and its repository now calls itself the former home of the now-withdrawn proposal. The DOM standard filled the gap: since promises have no built-in way to abort, AbortController gives APIs such as fetch an abort() method that changes the state of an AbortSignal.
Why it fits here: It answers this topic's question: promises have no cancel button, so a separate signal does the job.
Sources: TC39: proposal-cancelable-promises; WHATWG: DOM Standard
Two reasons to stop
One request may need two ways to stop: a Cancel button and a time limit. AbortSignal.any() takes several signals and returns one that aborts when any of them aborts, with the reason of the first. MDN shows it working across browsers since March 2024, and the DOM standard defines it.
Why it fits here: It joins this topic's two tools: a cancel by hand and a time limit can be combined into one signal for fetch.
Sources: MDN: AbortSignal.any(); WHATWG: DOM Standard
In one line
Give fetch a signal: AbortSignal.timeout(ms) sets a time limit, and an AbortController cancels by hand. Cancel the old request when a new one starts, or a late answer can overwrite a newer one: a race condition.
Other sites: origins and CORS
At a glance
A school lets parents read their own child's report card, but not every child's. Browsers guard pages from each other in a similar way.
An origin is a scheme, a host and a port together. A browser lets a script read answers only from its own origin, unless the other server allows it with an Access-Control-Allow-Origin header. That permission is called CORS. So the fix for a CORS error is always on the server, never in the page's own code.
Take a guess: Why must a server opt in before other sites may read its answers?
A page in your browser could, if nothing stopped it, ask your bank's site for your balance, using the login your browser already holds, and read the answer. So browsers have a rule: a script may read answers only from its own origin, unless the other site says otherwise.
The three parts at the start of an address: the scheme, the host and the port. https://shop.example:443 is one origin. If any of the three differs, it is another origin.
| Compared with https://shop.example/menu | Same origin? | Why |
|---|---|---|
| https://shop.example/cart | yes | only the path differs |
| http://shop.example/menu | no | another scheme |
| https://api.shop.example/menu | no | another host |
| https://shop.example:8443/menu | no | another port |
The kit's server can show this. Its page comes from 127.0.0.1, and the same server also answers to the name localhost. To a browser those are two hosts, so this request goes to another origin:
Served from 127.0.0.1, asking localhost
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const other = `http://localhost:${location.port}/stock.json`;
try {
const res = await fetch(other);
console.log((await res.json()).rice);
} catch (err) {
console.log(err.name, "|", err.message);
}
</script>
The server received
GET /stock.json
The Console shows
Error Access to fetch at 'http://localhost:.../stock.json' from origin 'http://127.0.0.1:...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Error Failed to load resource: net::ERR_FAILED
Info TypeError | Failed to fetch
Look closely at what happened. The request went out, and the server received it, as the notes under the block show. So CORS did not stop the request. It was the browser that refused to hand the answer to the script, and fetch rejected with the same TypeError as a dead server. The red line in the Console gives the real reason, and it says exactly what is missing.
Cross-Origin Resource Sharing: the rule by which a server allows pages from other origins to read its answers, by sending headers such as Access-Control-Allow-Origin. Browsers enforce it; other programs do not.
The fix is on the server, not in the page. When the server adds the header to its answer, the same script works:
The same page, with the server sending the header
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const other = `http://localhost:${location.port}/stock.json`;
try {
const res = await fetch(other);
console.log((await res.json()).rice);
} catch (err) {
console.log(err.name, "|", err.message);
}
</script>
The Console shows
Info 12
The star means any origin may read it, which suits public data. A private service names the one origin it trusts. For a request to another origin with a body of JSON, MDN explains that the browser first sends a small question, called a preflight, using the OPTIONS method, and sends the real request only if the server agrees.
| Who | Can fix a CORS error? |
|---|---|
| the page's script | no: nothing in fetch can make a blocked answer readable |
| the server that holds the data | yes: it sends the header |
| your own server | yes: it asks the other site itself, as CORS applies only in browsers, and passes the answer on |
Worked example 6
A shop's page at shop.example must load prices from api.shop.example, and gets the CORS error in the Console. Work out what is wrong, and what to change, from the error's own words.
What we have: the error's text, and the two addresses
What we need: the place to fix it, and the fix
The plan: compare the origins, read which header is missing, and change the server that answers
the Console's red line
Access to fetch at 'https://api.shop.example/prices' from origin 'https://shop.example'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
on the requested resource.
- The hosts differ, so these are two origins. The message says that the answer had no Access-Control-Allow-Origin header. So api.shop.example must send
Access-Control-Allow-Origin: https://shop.example.
Fix it on api.shop.example, by sending that header.
Check: the header names the page's origin, as the error names it.
A path that fails: adding the header to the request, in fetch's headers. The rule is about what the server allows, so a request cannot give itself permission, and the error stays.
When you are stuck: a request fails with a CORS error
Read the red line: it names both origins and the missing header.
Compare scheme, host and port: localhost and 127.0.0.1 are different hosts.
The fix belongs on the server that answers, or on a server of your own.
TypeError: Failed to fetch with no CORS line means the server was not reached at all.
Your turn
Are https://shop.example and https://shop.example/cart the same origin?Tap to reveal
- Only the path differs.
Yes.
Are http://shop.example and https://shop.example the same origin?Tap to reveal
- The scheme differs.
No.
Why can a page not fix a CORS error by itself?Tap to reveal
- The permission must come from the server that holds the data.
Because a request cannot give itself permission.
Did you know?
A rule from 1995
The rule that guards this topic began with JavaScript itself. Wikipedia dates the same-origin policy to Netscape Navigator 2.02 in 1995, shortly after JavaScript arrived in Netscape 2.0. The idea of an origin was written down as a standard only in December 2011, in RFC 6454, The Web Origin Concept, by Adam Barth of Google.
Why it fits here: It gives this topic's same-origin rule its history: browsers enforced it from 1995, long before a standard described it.
Sources: Wikipedia: Same-origin policy; RFC 6454: The Web Origin Concept
Why CORS asks permission
CORS works by permission for a reason. The Fetch standard explains that the CORS protocol lets responses declare that they can be shared with other origins. It needs to be an opt-in mechanism, the standard says, to prevent leaking data from responses behind a firewall, such as a company's intranet. A page on the open web must not read pages reachable only from inside an office.
Why it fits here: It answers this topic's question, and explains why the fix is on the server: only the server can give the permission.
Source: WHATWG: Fetch Standard
In one line
An origin is a scheme, a host and a port. A browser lets a script read answers only from its own origin, unless the other server allows it with Access-Control-Allow-Origin. The fix for a CORS error is always on the server.
Where it is used
Nearly every page that changes without reloading is fetching something. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| fetch and res.json() | data loaded after the page | a shop's prices, a school's results |
| res.ok and a helper | every request in a real program | a getJson used by the whole site |
| POST with JSON | forms, orders, anything saved | placing an order, booking a seat |
| URL and searchParams | searches, filters and page numbers | a search for rice & dal |
| time limits | every request to a server that may hang | giving up on a slow server after five seconds |
| cancelling | search as you type | dropping the search for te when tea is typed |
| CORS | pages that use another site's data | shop.example reading from api.shop.example |
Mistakes and debugging
These are the slips that people meet most often with fetch. Every message below is the real one, from Chrome.
1. The first await forgotten
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = fetch("stock.json");
console.log(res.ok);
</script>
The Console shows
Info undefined
No error: res is a promise, which has no ok. The fix: const res = await fetch("stock.json");.
2. The second await forgotten
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = await fetch("stock.json");
const data = res.json();
console.log(data.rice);
</script>
The Console shows
Info undefined
No error: data is a promise too. The fix: const data = await res.json();.
3. A body on a GET
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
await fetch("/orders", { body: "dosa" });
</script>
The Console shows
Error Uncaught TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
With no method, fetch uses GET, and a GET cannot carry a body. The fix: name the method: method: "POST".
4. An empty answer read as JSON
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const res = await fetch("/orders/7", { method: "DELETE" });
console.log(res.status, res.ok);
await res.json();
</script>
The Console shows
Info 204 true
Error Uncaught SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON input
A status of 204 means done, with no content, so there was nothing to parse. The fix: read the body only when there is one: res.status === 204 ? null : await res.json().
5. no-cors, in the hope of getting past CORS
Served from 127.0.0.1, asking localhost
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const other = `http://localhost:${location.port}/stock.json`;
const res = await fetch(other, { mode: "no-cors" });
console.log(res.type, res.status, res.ok);
</script>
The Console shows
Info opaque 0 false
The error is gone, and so is the answer: an opaque response hides its status and its body from the script. The fix: there is none in the page. The server must send the CORS header.
6. A signal that has already fired
On a real site, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
const controller = new AbortController();
controller.abort();
try {
await fetch("stock.json", { signal: controller.signal });
} catch (err) {
console.log(err.name);
}
try {
await fetch("stock.json", { signal: controller.signal });
} catch (err) {
console.log(err.name);
}
</script>
The Console shows
Info AbortError
Info AbortError
A controller stays aborted, so every request given its signal fails at once, and none reached the server. The fix: a new AbortController for each request.
The debugging corner: start in the Network panel
When a request misbehaves, open the Network panel before you change any code. No row means your code never made the request. A red row gives the status. A CORS line in the Console means the browser hid the answer. The Payload tab shows what you sent, and the Response tab what came back, so you can tell at once which side is wrong.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code, served by a small server
<!DOCTYPE html>
<meta charset="utf-8">
<title>Clock Tower</title>
<script type="module">
// one helper: a time limit, the status first, then the body
async function getJson(url, options) {
const res = await fetch(url, { signal: AbortSignal.timeout(3000), ...options });
if (!res.ok) throw new Error(`${url} answered ${res.status}`);
return res.json();
}
const stock = await getJson("stock.json");
console.log(stock.rice);
// sending: a method, a header, and JSON as text
const saved = await getJson("/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ item: "dosa" }),
});
console.log(saved.body);
// addresses: searchParams, never a gap
const url = new URL("/search", location.href);
url.searchParams.set("q", "tea & snacks");
console.log(url.search);
// a bad status is now an error like any other
try {
await getJson("missing.json");
} catch (err) {
console.log(err.message);
}
</script>
The Network panel shows
200 document /
200 fetch /stock.json
200 fetch /orders
404 fetch /missing.json
The Console shows
Info 12
Info {"item":"dosa"}
Info ?q=tea+%26+snacks
Error Failed to load resource: the server responded with a status of 404 (Not Found)
Info missing.json answered 404
| When you see | It means | Look at |
|---|---|---|
| undefined from res.ok or data.rice | a missing await | the two awaits |
SyntaxError: Unexpected token ... is not valid JSON | an error page read as JSON | res.ok before the body |
SyntaxError: ... Unexpected end of JSON input | an empty body read as JSON | the status, such as 204 |
TypeError: Failed to fetch | no answer reached the script | the address, the server, or a CORS line |
TypeError: ... body stream already read | the body read twice | keep the first read in a const |
blocked by CORS policy | another origin, with no permission | the header on that server |
| TimeoutError, AbortError | the request was called off | the limit, or who cancelled it |
The story: Read before you believe
You rewrite the morning request. The script now looks at the answer's status before it touches the body, and a bad status becomes an error of its own. If the Observatory says nothing for five seconds, the request is cancelled, and the clocks keep yesterday's time. Whatever went wrong is written in the log, in words.
The next morning the clerk moves the file again, and the clocks tick on while the log says why.
Master Verge reads the entry and closes the log. "Every answer from outside these walls is a stranger," he says. "Ask who it is before you let it in."
Reagents gathered: fetch, Response, status, JSON, AbortController, CORS.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)