JavaScript AJAX - Exercise 2
fetch() returns a Promise. While the request is still in progress, that promise remains pending until it fulfills with a response or rejects with a network error.
const requestPromise = fetch('/api/users');
console.log(requestPromise instanceof Promise); // trueThe options object configures the request, such as its method, headers, body, credentials, and cancellation signal. The response can then be parsed and used to update part of the page without a full navigation.
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ava' })
});Create a FormData object and send it as the request body. The browser will format it correctly for form submission. This keeps the interface responsive while the browser waits for the server.
const formData = new FormData();
formData.append('email', 'ava@example.com');
fetch('/subscribe', {
method: 'POST',
body: formData
});A fetch response body is a stream. Once you consume it with json(), text(), or another reader, that body cannot be read again. Parse it once and pass the resulting value to any code that needs it.
const response = await fetch('/message');
const text = await response.text();
console.log(text);
// Avoid calling response.json() after the body was already read.Read the content-type response header before deciding how to parse the body. The response can then be parsed and used to update part of the page without a full navigation.
const type = response.headers.get('content-type') || '';
if (type.includes('application/json')) {
const data = await response.json();
}A 204 No Content response means the request succeeded, but the server is not returning a response body. The response can then be parsed and used to update part of the page without a full navigation.
const response = await fetch('/api/tasks/42', {
method: 'DELETE'
});
console.log(response.status); // 204Add query parameters to the URL, preferably with URLSearchParams so values are encoded safely. The response can then be parsed and used to update part of the page without a full navigation.
const params = new URLSearchParams({ page: '2', sort: 'name' });
fetch(`/api/users?${params}`);Encoding prevents spaces and reserved URL characters from breaking the request or changing the intended meaning of the query. The response can then be parsed and used to update part of the page without a full navigation.
const query = encodeURIComponent('Ada Lovelace & Co');
fetch(`/search?q=${query}`);Create an AbortController, pass its signal to fetch(), and abort the request from a timer if it takes too long. The response can then be parsed and used to update part of the page without a full navigation.
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
fetch('/api/report', { signal: controller.signal });The credentials option controls whether the browser includes credentials such as cookies with the request and accepts credentialed responses, subject to CORS rules. The response can then be parsed and used to update part of the page without a full navigation.
fetch('https://api.example.com/profile', {
credentials: 'include'
});