JavaScript Tutorial
JavaScript Fetch
fetch(url) loads data. await response.json() parses JSON. Handle errors when the network or the URL fails.
Load data from a URL
fetch(url) asks the network for a resource. It returns a Promise. Withasync / await you write the steps in order: wait for the response, then parse the body.
For a first script, GET is enough — that is the default. You pass a URL and read JSON. You do not need extra options until you send data with POST.
await response.json()
fetch does not give you the object immediately. First you get aResponse. response.json() reads the body and parses it as JSON — the same job as JSON.parse, wired to the network.
Top-level await only works in modules. In a normal page script, put theawait inside an async function and call that function.
Example
<p id="out">Loading…</p>
<script>
async function loadTodo() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
const out = document.getElementById("out");
out.textContent = data.title;
console.log(data);
}
loadTodo();
</script>jsonplaceholder.typicode.com/todos/1is a public sample item. The JSON has userId, id,title, and completed. The page shows the title when the request succeeds.
Click Try it in JavaScript under an example. That opens/javascript/try — a live page and a console. The preview needs a network connection for fetch.
HTTP errors are not throws
fetch rejects (throws, when you await) on a network failure: offline, blocked, a bad host. A 404 or 500 still resolves. The Response arrives with ok set to false. Check response.ok (orresponse.status) before you parse.
Example
<p id="out">Loading…</p>
<script>
async function loadTodo() {
const out = document.getElementById("out");
const url = "https://jsonplaceholder.typicode.com/todos/1";
const response = await fetch(url);
if (!response.ok) {
out.textContent = "Request failed: " + response.status;
return;
}
const data = await response.json();
out.textContent = data.id + ": " + data.title;
}
loadTodo();
</script>try / catch for the network
Wrap the await calls in try / catch so a downed network does not stop the rest of the page with an uncaught error. Show a short message on the page. Log the error in the console for you.
Example
<p id="out">Loading…</p>
<script>
async function loadTodo() {
const out = document.getElementById("out");
try {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (!response.ok) {
throw new Error("status " + response.status);
}
const data = await response.json();
out.textContent = data.title;
} catch (err) {
out.textContent = "Could not load the todo.";
console.log(err.message);
}
}
loadTodo();
</script>What the sample looks like
The sample endpoint returns one object. You read fields with dots, the same as any parsed JSON. There is no special fetch type — after response.json() you have a normal object.
Example
<p id="out"></p>
<script>
async function loadTodo() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
const out = document.getElementById("out");
out.textContent =
"completed: " + data.completed +
" — user: " + data.userId;
console.log(JSON.stringify(data, null, 2));
}
loadTodo();
</script>Beginner limits
| Do | Wait on |
|---|---|
| GET a JSON URL | This chapter |
Check response.ok | This chapter |
try / catch around await | This chapter |
| POST, headers, CORS debugging | Later, when an API requires them |
If the console mentions CORS, the server refused this page’s origin. Public demo APIs such as JSONPlaceholder allow browser GET from a tutorial page. Your own server may need extra headers. That is a server setting, not a missing await.
What to remember
fetch(url)starts a request. Await theResponse.await response.json()parses a JSON body into an object.- Check
response.ok. A 404 does not throw by itself. - Catch network failures and show a message on the page.
You now have the language, the DOM, storage, and fetch. Open the examples shelf next and change a value in /javascript/try.