Sub topic 2
Inspecting the Response
This chapter assumes you can write async functions, use await, and know what HTTP status codes and headers are. It also assumes you have made a basic fetch() call, as the previous chapter showed.
When the Promise from fetch() fulfills, you get a Response object. At that point the server has sent its status line and headers, but the body may still be arriving. The Response lets you check what happened before you decide how to read the body.
The properties you check first
The table lists the properties you will use most. You can read all of them right away, without waiting for the body.
| Property | Type | What it tells you |
|---|---|---|
| `status` | number | The HTTP status code, such as `200`, `404`, or `500` |
| `ok` | boolean | `true` when `status` is from 200 to 299 |
| `statusText` | string | The reason phrase, such as `"Not Found"` |
| `headers` | `Headers` | The response headers |
| `url` | string | The final URL after any redirects |
| `redirected` | boolean | `true` if the request followed at least one redirect |
| `type` | string | `"basic"`, `"cors"`, `"opaque"`, and similar values that describe the response's origin |
A worked example
The Response constructor builds a response without touching the network. This lets you run the example in any browser console or in Node 18 and later.
function describe(response) {
return {
status: response.status,
ok: response.ok,
statusText: response.statusText,
contentType: response.headers.get('content-type'),
missingHeader: response.headers.get('x-not-there')
};
}
const found = new Response('{"id":1}', {
status: 200,
statusText: 'OK',
headers: { 'Content-Type': 'application/json' }
});
const missing = new Response('Not here', {
status: 404,
statusText: 'Not Found'
});
console.log(describe(found));
// { status: 200, ok: true, statusText: 'OK',
// contentType: 'application/json', missingHeader: null }
console.log(describe(missing));
// { status: 404, ok: false, statusText: 'Not Found',
// contentType: 'text/plain;charset=UTF-8', missingHeader: null }A few details in this output matter in practice:
headers.get()returnsnullfor a header that is absent. It does not returnundefinedor throw an error.- When the body is a string and you set no content type,
Responseaddstext/plain;charset=UTF-8. - The 404 response is still a normal fulfilled value, so nothing threw. The chapter on error handling builds on this.
Inspecting a real request
With a real network call, you check the same properties:
async function inspect(url) {
const response = await fetch(url);
console.log(response.status, response.ok);
console.log('Final URL:', response.url);
console.log('Redirected:', response.redirected);
console.log('Type:', response.headers.get('content-type'));
console.log('Length:', response.headers.get('content-length'));
return response;
}
inspect('https://jsonplaceholder.typicode.com/todos/1');Open the network panel next to the console. The status and headers shown there should match what your code logs, with one exception covered in the next section.
Common mistakes
- Reading headers the server didn't expose. In a cross-origin response, JavaScript can see only the CORS-safelisted headers (such as
Content-Type) unless the server lists others inAccess-Control-Expose-Headers. The network panel shows every header, butheaders.get()returnsnullfor the hidden ones. - Trusting
content-length. Compressed or chunked responses may leave it out. Treat it as a hint, never as a guaranteed value. - Treating
okas "the data is valid".okonly describes the status code. A200response can still carry an error payload or HTML from a misconfigured proxy, so checkcontent-typewhen the format matters. - Comparing
urlwith the URL you requested. After a redirect,response.urlis the final address. Useredirectedif you need to know whether that happened.
Exercise
A request returns a Response with status 304. What is the value of response.ok, and why?
Show answer
false. The ok property is true only for statuses from 200 to 299, and 304 Not Modified is outside that range. (Browsers often handle 304 internally and show your code a 200 from the cache instead.)
Exercise
Your code calls response.headers.get('X-Request-Id') on a cross-origin response and gets null, but the network panel shows the header. What is the likely cause and fix?
Show answer
The server has not exposed the header through CORS. Only safelisted response headers are readable from JavaScript, so the server must add "Access-Control-Expose-Headers: X-Request-Id".