iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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 / methodReturns
res.status / res.statusTextHTTP code / message.
res.okTrue for 200–299.
res.redirectedTrue if the URL changed.
res.urlFinal 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.bodyA 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);

Test yourself

Q1. res.ok is true for…
Q2. Read a Response body twice by…
Q3. Stream a large download with…

Discussion

Loading…