Making HTTP Requests
The Fetch API provides a modern interface for making HTTP requests to servers, replacing the older XMLHttpRequest.
Fetch returns Promises, making it perfect to use with async/await for cleaner, more readable code.
You can fetch data from APIs, submit forms, upload files, and handle various HTTP methods (GET, POST, PUT, DELETE) and response types.
// Basic GET request
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// Using async/await (preferred)
async function fetchUsers() {
try {
const response = await fetch('https://api.example.com/users');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
// POST request with JSON data
async function createUser(userData) {
try {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(userData)
});
const result = await response.json();
return result;
} catch (error) {
console.error('Error creating user:', error);
}
}
// Different response types
const textData = await response.text(); // Plain text
const jsonData = await response.json(); // JSON
const blobData = await response.blob(); // Binary (images, files)
- fetch(url) - Make HTTP request, returns Promise
- response.json() - Parse JSON response body
- response.text() - Get response as plain text
- response.ok - Boolean, true if status is 200-299
- response.status - HTTP status code (200, 404, etc.)
- method - HTTP method: GET, POST, PUT, DELETE, etc.
- headers - Set request headers (Content-Type, Authorization, etc.)
- body - Request body for POST/PUT requests
Try Fetch API
<div class="fetch-demo">
<h3>Fetch API Examples</h3>
<div class="example">
<h4>1. Fetch Users (GET Request)</h4>
<button id="fetchUsersBtn">Fetch Users</button>
<div id="usersOutput"></div>
</div>
<div class="example">
<h4>2. Fetch Single User</h4>
<input type="number" id="userId" value="1" min="1" max="10">
<button id="fetchUserBtn">Fetch User</button>
<div id="userOutput"></div>
</div>
<div class="example">
<h4>3. Create Post (POST Request)</h4>
<input type="text" id="postTitle" placeholder="Post title">
<textarea id="postBody" placeholder="Post content"></textarea>
<button id="createPostBtn">Create Post</button>
<div id="postOutput"></div>
</div>
</div>
Note: CORS: Cross-Origin Resource Sharing restrictions may prevent requests to some APIs from browsers.
Note: Error Handling: Always check response.ok and handle network errors with try/catch.
Note: API Keys: Never expose API keys in client-side code. Use environment variables or backend proxy for sensitive requests.