Master the modern Fetch API for making HTTP requests in JavaScript with async/await patterns and professional error handling.
The Fetch API is the modern standard for making HTTP requests in JavaScript, replacing the older XMLHttpRequest. It provides a more powerful and flexible feature set with a cleaner, promise-based interface that works seamlessly with modern JavaScript patterns.
The Fetch API provides a JavaScript interface for accessing and manipulating HTTP requests and responses. It's built into modern browsers and offers a more powerful and flexible feature set than XMLHttpRequest.
Basic Fetch syntax:
1fetch(url, options)
2 .then(response => {
3 // Handle response
4 return response.json(); // or .text(), .blob(), etc.
5 })
6 .then(data => {
7 // Handle data
8 console.log(data);
9 })
10 .catch(error => {
11 // Handle errors
12 console.error('Fetch error:', error);
13 });Simple GET request:
1// Fetch user data
2fetch('https://jsonplaceholder.typicode.com/users/1')
3 .then(response => {
4 if (!response.ok) {
5 throw new Error('HTTP error! status: ' + response.status);
6 }
7 return response.json();
8 })
9 .then(user => {
10 console.log('User name:', user.name);
11 console.log('User email:', user.email);
12 })
13 .catch(error => {
14 console.error('Failed to fetch user:', error);
15 });Modern JavaScript offers two primary patterns for handling asynchronous operations: Promises with .then() chains and async/await syntax.
Traditional Promise chain:
1function getUserData(userId) {
2 return fetch('https://api.example.com/users/' + userId)
3 .then(response => {
4 if (!response.ok) {
5 throw new Error('User not found: ' + response.status);
6 }
7 return response.json();
8 })
9 .then(user => {
10 console.log('User loaded:', user.name);
11 return user;
12 })
13 .catch(error => {
14 console.error('Error loading user:', error);
15 throw error;
16 });
17}Modern async/await syntax:
1async function getUserData(userId) {
2 try {
3 const response = await fetch('https://api.example.com/users/' + userId);
4
5 if (!response.ok) {
6 throw new Error('User not found: ' + response.status);
7 }
8
9 const user = await response.json();
10 console.log('User loaded:', user.name);
11 return user;
12
13 } catch (error) {
14 console.error('Error loading user:', error);
15 throw error;
16 }
17}Advantages of async/await:
The Fetch API's second parameter allows you to configure requests with custom headers, HTTP methods, and request bodies.
POST request configuration:
1async function createUser(userData) {
2 const response = await fetch('/api/users', {
3 method: 'POST',
4 headers: {
5 'Content-Type': 'application/json',
6 'Authorization': 'Bearer your-token-here'
7 },
8 body: JSON.stringify(userData)
9 });
10
11 if (!response.ok) {
12 throw new Error('Failed to create user');
13 }
14
15 return await response.json();
16}
17
18// Usage
19const newUser = await createUser({
20 name: 'Jane Smith',
21 email: '[email protected]',
22 role: 'user'
23});Response handling methods:
1const response = await fetch('/api/data');
2
3// For JSON data
4const jsonData = await response.json();
5
6// For plain text
7const textData = await response.text();
8
9// For binary data (images, files)
10const blobData = await response.blob();
11
12// Check response properties
13console.log(response.status); // 200, 404, 500, etc.
14console.log(response.statusText); // "OK", "Not Found", etc.
15console.log(response.ok); // true if status 200-299
16console.log(response.headers); // Headers objectError handling best practices:
1async function robustFetch(url, options = {}) {
2 try {
3 const response = await fetch(url, options);
4
5 // Check for HTTP errors
6 if (!response.ok) {
7 throw new Error('HTTP ' + response.status + ': ' + response.statusText);
8 }
9
10 // Check content type
11 const contentType = response.headers.get('content-type');
12 if (!contentType || !contentType.includes('application/json')) {
13 throw new Error('Response is not JSON');
14 }
15
16 return await response.json();
17
18 } catch (error) {
19 if (error.name === 'TypeError') {
20 throw new Error('Network error or invalid URL');
21 } else {
22 throw error;
23 }
24 }
25}Your progress is saved in this browser, on this device only.