JavaScript Fetch
About JavaScript Fetch
In JavaScript, fetch is a built-in function that allows you to make network requests (like GET, POST, PUT, DELETE) to retrieve resources from a server. It is part of the Fetch API, which provides a modern way to handle HTTP requests and responses in web applications.
It provides a more powerful and flexible way to fetch resources asynchronously over the network compared to older methods like XMLHttpRequest.
The fetch function returns a Promise that resolves to the Response object. This allows you to handle the response asynchronously, making it easier to work with network requests without blocking the main thread.
Basic Components of Fetch Request
fetch() Function
- fetch(url, options) : The core function used to make network requests. It takes a URL as its first argument and an optional configuration object as its second argument.
Request options (Optional)
- method : HTTP method (GET, POST, PUT, DELETE, etc.).
- headers : Request headers (e.g., { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-token-here' }).
- body : Data to send (for POST, PUT—usually a string, object, FormData, or Blob).
- mode : CORS mode (cors, no-cors, same-origin).
- credentials : Whether to send cookies (include, same-origin, omit).
- cache : Cache behavior (default, no-store, reload, etc.).
Response Object
The Response object represents the response to a request. It contains properties and methods to access the response data, such as status, statusText, headers, and methods like json(), text(), etc.
- response.ok : Boolean (true if status 200-299).
- response.status : HTTP status code (e.g., 200, 404, 500).
- response.headers : Access response headers.
- response.json() : Returns the response body as JSON.
- response.text() : Returns the response body as text.
- response.blob() : Returns the response body as a Blob (for binary data e.g., images).
Handling the Response
After making a fetch request, you can handle the response using the .then() method to process the data or handle errors with .catch(). You can also use .finally() to execute code after the request is complete, regardless of success or failure.
- .then(response => response.json()) : Parses the response as JSON.
- .then(data => { ... }) : Handles the parsed data.
- .catch(error => { ... }) : Handles errors that occur during the fetch request.
- .finally(() => { ... }) : Executes code after the request is complete, regardless of success or failure.
Error Handling
If the fetch request fails (e.g., network error, server error), it will reject the Promise, and you can handle the error using the .catch() method.
You can manually check the error status using the response.ok property, which returns true if the response status is in the range of 200-299. If the response is not OK, you can throw an error or handle it accordingly.
Basic Fetch (GET) Request
The simplest form of a fetch request takes one argument (URL or the path to the resource) and returns a promise that resolves to a Response object.
The following example demonstrates how to make a basic GET request using the fetch function. In this example, we are fetching a list of products from a dummy API.
GET Request With ID
You can also make a GET request to fetch a specific resource by providing its ID in the URL.
The following example demonstrates how to fetch a product with a specific ID (e.g., 2) from the same dummy API.
Making POST Request
The POST request is made to send data to a server. To make a POST request, you need to provide an options object with method, headers and a body.
The body should be a stringified JSON object or FormData, depending on the content type you are sending.
The following example demonstrates how to make a POST request using the fetch function, sending a JSON object to the server.
Making PUT Request
The PUT request is used to update an existing resource on the server. It is similar to a POST request, but it typically replaces the entire resource with the new data provided in the request body.
To make a PUT request, you need to provide an options object with method, headers, and a body.
The body should be a stringified JSON object or FormData, depending on the content type you are sending.
The following example demonstrates how to make a PUT request using the fetch function, sending a JSON object to the server.
Making PATCH Request
The PATCH request is used to apply partial modifications to a resource on the server. It is similar to a PUT request, but it only updates the specified fields rather than replacing the entire resource.
The following example demonstrates how to make a PATCH request using the fetch function, sending a JSON object to the server. In this example, we are updating the price of a product with Id 3.
Making DELETE Request
The DELETE request is used to delete a resource on the server. It is typically used to remove an existing resource identified by a specific URL.
The following example demonstrates how to make a DELETE request using the fetch function. In this example, we are deleting a product with Id 3.
Fetch With Async/Await
The async/await syntax provides a more readable and synchronous-looking way to work with asynchronous code, including fetch requests. It allows you to write asynchronous code that looks like synchronous code, making it easier to read and maintain.
Sending Form Data
You can also send form data using the fetch function. To do this, you can use the FormData object, which allows you to easily construct a set of key/value pairs representing form fields and their values.
To send form data (multipart/form-data), you can create a FormData object and pass it as the body of the fetch request. The fetch function will automatically set the appropriate headers for you.
The following example demonstrates how to send form data using the fetch function.
Canceling Fetch Request
You can cancel a fetch request using the AbortController. The AbortController allows you to create a signal that can be used to abort a fetch request if it takes too long or if you no longer need the response.
To cancel a fetch request, you can create an instance of AbortController, get its signal, and pass it as an option to the fetch function.
The following example demonstrates how to cancel a fetch request using the AbortController. In this example, we set a timeout to abort the request after 3 seconds, while the server responds in 7 seconds.
JavaScript Compiler For Live Practice
Practice the above JavaScript code in the following JavaScript Compiler. Create more fetch requests in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.
JavaScript Compiler