ajax_fetch_response
Handling Server Responses with Fetch
Section titled “Handling Server Responses with Fetch”The Response Object
Section titled “The Response Object”When a fetch request successfully completes, the promise resolves with a Response object. This object contains information about the response (like status code, headers) and methods to access the response body.
Important: The Response object doesn’t directly contain the body data. You need to call one of its body-reading methods, which themselves return promises.
Key Response Properties:
Section titled “Key Response Properties:”| Property | Description |
|---|---|
response.ok | A boolean indicating if the HTTP status code is in the successful range (200-299). Returns true for success, false otherwise. |
response.status | The numerical HTTP status code of the response (e.g., 200, 404, 500). |
response.statusText | The status message corresponding to the status code (e.g., "OK", "Not Found"). |
response.headers | A Headers object allowing you to query the response headers (e.g., response.headers.get('Content-Type')). |
response.url | The URL of the resource that provided the response (useful if redirects occurred). |
Checking for Success
Section titled “Checking for Success”Always check response.ok before attempting to read the body. A 404 (Not Found) or 500 (Internal Server Error) response is still a ‘successful’ fetch completion in terms of network communication, but it’s not a successful application-level response.
async function fetchData(url) { try { const response = await fetch(url);
if (!response.ok) { // Check for HTTP errors // You could get more specific error info from response.status or response.statusText throw new Error(`HTTP error! Status: ${response.status}`); }
// Proceed only if response.ok is true const data = await response.json(); // Or .text(), .blob() etc. console.log(data);
} catch (error) { // This catches both network errors (fetch failure) and HTTP errors thrown above console.error('Fetch error:', error); }}
fetchData('https://api.example.com/data');fetchData('https://api.example.com/nonexistent'); // Example to trigger a 404Reading the Response Body
Section titled “Reading the Response Body”The Response object provides methods to read the body in different formats. These methods return promises that resolve with the actual body content. You can only read the body ONCE per response.
| Method | Description |
|---|---|
response.json() | Reads the response body and attempts to parse it as JSON. Returns a promise that resolves with the resulting JavaScript object or array. |
response.text() | Reads the response body as plain text. Returns a promise that resolves with a string. |
response.blob() | Reads the response body as a Blob (Binary Large Object), useful for images, files, etc. Returns a promise resolving with the Blob. |
response.formData() | Reads the response body as FormData. Returns a promise resolving with the FormData object. |
response.arrayBuffer() | Reads the response body as an ArrayBuffer (raw binary data). Returns a promise resolving with the ArrayBuffer. |
Example: Reading JSON
Section titled “Example: Reading JSON”This is the most common scenario when working with web APIs.
async function getUserData(userId) { try { const response = await fetch(`/api/users/${userId}`); if (!response.ok) { throw new Error(`Error fetching user: ${response.status}`); }
// Read and parse the JSON body const userData = await response.json();
console.log('User Name:', userData.name); document.getElementById('userInfo').textContent = `User: ${userData.name}, Email: ${userData.email}`;
} catch (error) { console.error('Could not get user data:', error); document.getElementById('userInfo').textContent = 'Failed to load user data.'; }}
getUserData(123);Example: Reading Text
Section titled “Example: Reading Text”Useful for fetching HTML snippets, plain text files, or configurations.
async function loadContent(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`Failed to load content: ${response.status}`); }
// Read the body as text const textContent = await response.text();
document.getElementById('contentArea').innerHTML = textContent; // Be careful with innerHTML if content isn't trusted
} catch (error) { console.error('Error loading content:', error); document.getElementById('contentArea').textContent = 'Could not load content.'; }}
loadContent('data/about.txt');Common Pitfall: Forgetting await on body methods or checking response.ok.
Learn more about the Response object on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Response