AJAX Response
An AJAX response is the Response object you get back from fetch (or XHR's responseText / response). Status, headers, and body are the three pieces to inspect.
The Response object
| Property / method | Returns |
|---|---|
res.status / res.statusText | HTTP code / message. |
res.ok | True for 200–299. |
res.redirected | True if the URL changed. |
res.url | Final URL after redirects. |
res.headers.get("Content-Type") | One header. |
res.json() / res.text() | Body parsed. |
res.blob() | Binary for downloads/images. |
res.arrayBuffer() | Lower-level binary. |
res.formData() | If the body is form-encoded. |
res.body | A ReadableStream — for streaming or progress. |
Status checking
JS
const res = await fetch(url);
if (!res.ok) { // anything outside 2xx
if (res.status === 401) redirectToLogin();
else if (res.status === 404) showNotFound();
else throw new Error(`HTTP ${res.status}`);
}
const data = await res.json();
Read body multiple times — clone first
JS
const res = await fetch(url); const text = await res.clone().text(); // peek as text const json = await res.json(); // … then as JSON // Without clone(), the second read throws because the body is consumed
Streaming a large download
JS
const res = await fetch("/big.json");
const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) break;
process(decoder.decode(value, { stream: true }));
}
Gotcha: Each
.json() / .text() consumes the body. If you need to read it twice, call res.clone() first.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from AJAX Response!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Check that the response status was 2xx.
if (!res.
) throw new Error('HTTP ' + res.status);
Two letters.
Discussion
Loading…