Make HTTP requests with the Fetch API and handle JSON responses. Learn the correct error-checking pattern for async requests.
Note: Fetch makes real network requests — they will be blocked in this sandbox. The code shows the correct patterns; run in a browser or Node.js 18+ to test live.
// GET request
async function getUser(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json(); // parses JSON body
}
// POST request
async function createPost(data) {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
async function main() {
try {
const user = await getUser(1);
console.log(user.name);
const post = await createPost({ title: 'Hello', body: 'World', userId: 1 });
console.log('Created post id:', post.id);
} catch (err) {
console.log('Error:', err.message);
}
}
console.log('Fetch patterns:');
console.log(' GET: fetch(url)');
console.log(' POST: fetch(url, { method, headers, body })');
console.log(' Always check res.ok before calling res.json()');
// main(); // uncomment to run in browser