Fetch API - Exercise 2
Set the method and content type, then serialize the object with JSON.stringify(). Handle both network failures and unsuccessful HTTP status codes before using the response data.
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. Handle both network failures and unsuccessful HTTP status codes before using the response data. The example shows where that result becomes available to the rest of the program.
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. Handle both network failures and unsuccessful HTTP status codes before using the response data.
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. Handle both network failures and unsuccessful HTTP status codes before using the response data.
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. Handle both network failures and unsuccessful HTTP status codes before using the response data.
const [usersResponse, postsResponse] = await Promise.all([
fetch('/api/users'),
fetch('/api/posts')
]);Set credentials according to the server’s cookie and CORS policy. Handle both network failures and unsuccessful HTTP status codes before using the response data. The example shows where that result becomes available to the rest of the program.
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. Handle both network failures and unsuccessful HTTP status codes before using the response data.
const response = await fetch('/api/profile', {
headers: { Authorization: `Bearer ${token}` }
});Parse the response, transform the collection, then pass the view model to the renderer. Handle both network failures and unsuccessful HTTP status codes before using the response data.
const users = await safeFetch('/api/users');
const names = users.map(user => user.name).sort();
renderNames(names);Set the method, JSON content type, and serialized request body before checking the response.
await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ada' })
});Use the credentials option when cookies or other browser-managed credentials must be sent.
const response = await fetch('/api/profile', {
credentials: 'include'
});