Fetch API - Exercise 2
Set the method and content type, then serialize the object with JSON.stringify().
const response = await fetch('/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Hello' })
});Centralize the response.ok check, then return the parsed JSON.
async function safeFetch(url, options) {
const response = await fetch(url, options);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}Use PUT with a JSON body and the appropriate request header.
await fetch('/api/users/7', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ada' })
});Send a DELETE request to the resource URL and check the response.
const response = await fetch('/api/users/7', {
method: 'DELETE'
});
if (!response.ok) throw new Error('Delete failed');Pass the fetch Promises to Promise.all() so they start without waiting for one another.
const [usersResponse, postsResponse] = await Promise.all([
fetch('/api/users'),
fetch('/api/posts')
]);Set credentials according to the server’s cookie and CORS policy.
const response = await fetch('https://api.example.com/me', {
credentials: 'include'
});Include the token in the request headers, usually with the server’s expected scheme.
const response = await fetch('/api/profile', {
headers: { Authorization: `Bearer ${token}` }
});Parse the response, transform the collection, then pass the view model to the renderer.
const users = await safeFetch('/api/users');
const names = users.map(user => user.name).sort();
renderNames(names);