fetch() loads data from a server without reloading the page.
GET data
const res = await fetch('https://api.example.com/users');
if (!res.ok) throw new Error('HTTP ' + res.status);
const users = await res.json();
Steps
fetch(url)returns a Promise of a Response- Check
res.ok(status 200–299) - Read the body with
res.json()orres.text()
POST data
await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Asha' })
});
fetch only rejects on network failure — a 404 or 500 still "succeeds", so always check res.ok.
Example
Example — Load users from an API
HTML
<button id="load">Load users</button>
<ul id="users"></ul>
<p id="msg"></p>
<script>
document.getElementById('load').onclick = async () => {
const msg = document.getElementById('msg');
const list = document.getElementById('users');
msg.textContent = 'Loading...';
list.innerHTML = '';
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
if (!res.ok) throw new Error('HTTP ' + res.status);
const users = await res.json();
for (const u of users) {
const li = document.createElement('li');
li.textContent = `${u.name} – ${u.address.city}`;
list.append(li);
}
msg.textContent = users.length + ' users loaded.';
} catch (err) {
msg.textContent = 'Could not load data: ' + err.message;
}
};
</script>
Uses the free JSONPlaceholder test API.
Try it Now »