fetch API in JavaScript
The fetch
API in JavaScript is a powerful tool for making HTTP requests to servers. It provides a simpler and more flexible way to make network requests compared to the older XMLHttpRequest
API. Here’s a detailed explanation of the fetch
API and its options:
Basic Usage
The most basic usage of fetch
involves calling it with a URL:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Fetch Options
The fetch
function can take a second argument, an options object, to configure the request. Here are all the possible options:
-
Method
method
: The HTTP method to use (e.g.,GET
,POST
,PUT
,DELETE
).
fetch('https://api.example.com/data', { method: 'POST' });
-
Headers
headers
: An object representing the headers to include in the request.
fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token' } });
-
Body
body
: The body of the request. This can be aBlob
,BufferSource
,FormData
,URLSearchParams
,ReadableStream
, orUSVString
.
fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) });
-
Mode
mode
: The mode of the request (e.g.,cors
,no-cors
,same-origin
).
fetch('https://api.example.com/data', { mode: 'cors' });
-
Credentials
credentials
: Indicates whether to send cookies with the request. Options areomit
,same-origin
, orinclude
.
fetch('https://api.example.com/data', { credentials: 'include' });
-
Cache
cache
: The cache mode of the request (e.g.,default
,no-store
,reload
,no-cache
,force-cache
,only-if-cached
).
fetch('https://api.example.com/data', { cache: 'no-cache' });
-
Redirect
redirect
: How to handle redirects (e.g.,follow
,error
,manual
).
fetch('https://api.example.com/data', { redirect: 'follow' });
-
Referrer
referrer
: A string specifying the referrer of the request.
fetch('https://api.example.com/data', { referrer: 'client' });
-
Referrer Policy
referrerPolicy
: The referrer policy (e.g.,no-referrer
,no-referrer-when-downgrade
,origin
,origin-when-cross-origin
,unsafe-url
).
fetch('https://api.example.com/data', { referrerPolicy: 'no-referrer' });
-
Integrity
integrity
: Contains the subresource integrity value of the request.
fetch('https://api.example.com/data', { integrity: 'sha256-abcdef' });
-
Keepalive
keepalive
: Boolean that indicates whether the request can outlive the page.
fetch('https://api.example.com/data', { keepalive: true });
-
Signal
signal
: AnAbortSignal
to abort the request.
const controller = new AbortController(); const signal = controller.signal; fetch('https://api.example.com/data', { signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => { if (error.name === 'AbortError') { console.log('Request aborted'); } }); // Abort the request controller.abort();
Complete Example
Here's a complete example using many of these options:
const controller = new AbortController();
const signal = controller.signal;
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
body: JSON.stringify({ key: 'value' }),
mode: 'cors',
credentials: 'include',
cache: 'no-cache',
redirect: 'follow',
referrer: 'client',
referrerPolicy: 'no-referrer',
integrity: 'sha256-abcdef',
keepalive: true,
signal
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request aborted');
} else {
console.error('Error:', error);
}
});
// To abort the request
controller.abort();
Published on: Aug 01, 2024, 01:20 AM