Junior
What does the fetch method accept?
sobes.tech AI
Answer from AI
The fetch method takes one mandatory argument — the request path (RequestInfo or URL) — and one optional argument — a settings object (RequestInit).
Mandatory argument (input):
- String: URL of the resource.
Requestobject: An instance of theRequestclass, providing more flexible request configuration (headers, method, etc.).
Optional argument (init): An object with fields describing request settings. Some commonly used fields:
method: HTTP request method (GET,POST,PUT,DELETE,OPTIONS, etc.).headers: Request headers. Can be an object of key-value pairs or an instance of theHeadersclass.body: Request body (for methods other thanGETorHEAD). Can be a string,ArrayBuffer,TypedArray,DataView,Blob,FormData,URLSearchParams, orReadableStream.mode: Request mode (cors,no-cors,same-origin,navigate).credentials: Credential sending configuration (omit,same-origin,include).cache: Caching configuration (default,no-store,reload,no-cache,force-cache,only-if-cached).redirect: How to handle redirects (follow,error,manual).referrer: Value for theRefererheader.referrerPolicy: Policy for sending theRefererheader.integrity: Value for theIntegrityheader. Used for Subresource Integrity.keepalive: Boolean indicating that the request should remain active after the page is closed (for sending analytics or reports).signal: AnAbortSignalinstance for canceling the request.window: The Window object associated with the request (defaults to the current window).
Example usage:
// GET request
fetch('/api/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// POST request with body and headers
fetch('/api/products', {
method: 'POST', // HTTP method
headers: {
'Content-Type': 'application/json', // Data type
'Authorization': 'Bearer your_token' // Example authorization header
},
body: JSON.stringify({ name: 'New product', price: 100 }) // Request body
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));