AJAX Response
Handling Server Responses with Fetch
Section titled “Handling Server Responses with Fetch”The Fetch API provides a modern and flexible way to handle responses from server requests.
The Response Object
Section titled “The Response Object”When a fetch request is successful, it returns a Promise that resolves to a Response object. This object contains information about the response (like status code, headers) and methods to access the response body.
Key Properties and Methods of the Response Object:
Section titled “Key Properties and Methods of the Response Object:”| Property/Method | Description |
|---|---|
response.ok | A boolean indicating if the HTTP status code is in the successful range (200-299). |
response.status | The 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 access to response headers. |
response.text() | Returns a Promise that resolves with the response body as a string. |
response.json() | Returns a Promise that resolves with the result of parsing the response body text as JSON. |
response.blob() | Returns a Promise that resolves with the response body as a Blob (binary data). |
response.formData() | Returns a Promise that resolves with the response body as FormData. |
response.arrayBuffer() | Returns a Promise that resolves with the response body as an ArrayBuffer. |
Important: Methods like .json(), .text(), etc., consume the response body. You can only use one of these methods once per Response object.
Handling Text Responses
Section titled “Handling Text Responses”If you expect plain text from the server, use the response.text() method:
fetch('data.txt') .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.text(); // Get the response body as text }) .then(textData => { console.log('Received text:', textData); document.getElementById('myDiv').textContent = textData; // Display the text }) .catch(error => { console.error('Error fetching text data:', error); document.getElementById('myDiv').textContent = 'Failed to load data.'; });Handling JSON Responses
Section titled “Handling JSON Responses”JSON is the most common format for APIs. Use response.json() to parse it directly into a JavaScript object or array:
async function fetchUserData() { const userInfoDiv = document.getElementById('userInfo'); try { const response = await fetch('/api/user/123'); // Example API endpoint
if (!response.ok) { throw new Error(`API Error: ${response.status} ${response.statusText}`); }
const userData = await response.json(); // Parse the JSON response body
console.log('Received user data:', userData); // Assuming userData is like { name: 'Alice', email: 'alice@example.com' } userInfoDiv.innerHTML = `<h2>${userData.name}</h2><p>Email: ${userData.email}</p>`;
} catch (error) { console.error('Failed to fetch user data:', error); userInfoDiv.textContent = `Error loading user data: ${error.message}`; }}
fetchUserData();This example uses async/await for cleaner asynchronous code.
Checking the Response Status
Section titled “Checking the Response Status”Always check the response.ok property or the response.status code before processing the body. A 404 (Not Found) or 500 (Internal Server Error) is still a ‘successful’ fetch from a network perspective, but indicates an application-level error.
fetch('/api/some-resource') .then(response => { if (!response.ok) { // Handle specific errors based on status code if (response.status === 404) { throw new Error('Resource not found (404)'); } else if (response.status === 500) { throw new Error('Server error (500)'); } else { throw new Error(`Unexpected problem: ${response.status}`); } } return response.json(); // Only parse if status is OK }) .then(data => { console.log('Data received:', data); }) .catch(error => { console.error('Fetch operation failed:', error); // Update UI to inform the user about the error });For more details on handling different data types and advanced response features, refer to the MDN documentation for the Fetch API.