Learn how to make HTTP requests using the native Fetch API
Click the button to fetch random user data from an API:
// Fetch data from API
async function fetchRandomUser() {
try {
// Show loading state
resultDiv.innerHTML = '<div class="loading">Loading...</div>';
// Make the request (using GitHub API with CORS)
const response = await fetch('https://api.github.com/users/torvalds');
// Check if response is ok
if (!response.ok) {
throw new Error(\`HTTP Error: \${response.status}\`);
}
// Parse JSON
const user = await response.json();
// Display the data
displayUser(user);
} catch (error) {
// Handle errors
resultDiv.innerHTML = \`
<div class="error">
Error: \${error.message}
</div>
\`;
}
}
function displayUser(user) {
resultDiv.innerHTML = \`
<div class="user-card">
<img src="\${user.avatar_url}" alt="\${user.name}">
<div class="user-info">
<h3>\${user.name || user.login}</h3>
<p><strong>Username:</strong> \${user.login}</p>
<p><strong>Bio:</strong> \${user.bio || '(No bio)'}</p>
<p><strong>Repos:</strong> \${user.public_repos}</p>
</div>
</div>
\`;
}
// POST request
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
});
// With query parameters
const params = new URLSearchParams({ page: 1, limit: 10 });
const response = await fetch(\`/api/users?\${params}\`);
// With authentication
const response = await fetch('/api/data', {
headers: {
'Authorization': 'Bearer ' + token
}
});