fetch and APIs
fetch() makes HTTP requests from JavaScript: loading data from an API, submitting a form, calling your own back end. It returns a promise, so it pairs naturally with await.
A GET request
This example fetches CodeMIRAI's own course list, which is a real JSON file on this site:
const response = await fetch(location.origin + "/data/tracks.json");
console.log("Status:", response.status, response.ok);
const courses = await response.json(); // parse the body as JSON
console.log("Courses:", courses.length);
for (const c of courses.slice(0, 5)) {
console.log(`${c.name}: ${c.modules.length} modules`);
}Two awaits: one for the response to arrive, one for its body to be read and parsed.
Check the status
fetch only rejects when the network fails. A 404 or 500 still fulfills, with response.ok set to false, so check it:
async function getJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status} for ${url}`);
}
return response.json();
}
try {
await getJSON(location.origin + "/data/does-not-exist.json");
} catch (err) {
console.log("Caught:", err.message);
}Sending data: POST
const response = await fetch("https://api.example.com/feedback", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ rating: 5, comment: "Great lesson!" }),
});
const result = await response.json();The options object sets the method, the headers, and the body (as a string).
Common status codes
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created (after a successful POST) |
| 400 | Bad request: the data you sent was invalid |
| 401 / 403 | Not signed in / not allowed |
| 404 | Not found |
| 429 | Too many requests: slow down |
| 500 | Server error |
CORS
A page can only fetch from another website if that site allows it, through headers known as CORS. Public APIs designed for browsers send those headers; many others don't, in which case the request has to go through your own server.