Fetch is a built-in web API in JavaScript that allows us to make a network request. From fetching data from a server or sending data to a server.
The Fetch API was primarily driven by a team of developers from various companies, including Mozilla, Google, Microsoft, and others who were part of the WHATWG. It became widely adopted in modern browsers and is now a standard feature of JavaScript, providing a more modern and powerful mechanism for making network requests and handling responses.
With the Fetch, you can make various types of requests, including:
- GET Request: Fetch data from a server.
- POST Request: Send data to a server to create a new resource.
- PUT Request: Send data to a server to update an existing resource.
- DELETE Request: Request a server to delete a resource.
- HEAD Request: Similar to GET, but only fetches the headers, not the content.
- PATCH Request: Partially update a resource on the server.
- OPTIONS Request: Retrieve information about the communication options available for a resource.
You can specify the HTTP method when making a fetch request by providing the appropriate method name in the options object as the second argument to the fetch function.
GET Request
To make a GET request, you use the fetch function and provide the URL you want to fetch data from. fetch returns a Promise that resolves to the Response object containing the data.
Post Request
To make a POST request and send data to the server, you provide an options object as the second argument to fetch, which includes the method, headers, and body.
In this example, we send a JSON object (dataToSend) as the payload in the request body. We set the Content-Type header to 'application/json' to indicate that we are sending JSON data.
When the server receives the POST request, it can access the sent data in the request body and process it accordingly. Always ensure that the server-side API is set up to handle POST requests and respond appropriately.
The Response
When using the Fetch API, you can handle the response from the server using the .then() and .catch() methods, which are part of the Promises returned by the fetch function. The response object contains useful information such as headers, status, and the data returned from the server.
Depending on what response you get like JSON data you can use .json() method to parse the response and extract the data. This method also returns a Promise, so you can chain another .then() to handle the parsed data. As shown above. Another type of response could be a plain text instead of JSON, you can use the .text() method to read the response as text.
When handling errors you can use the .catch() method at the end of the fetch chain to handle any that occur during the fetch.
Remember to use the appropriate HTTP method that matches the operation you want to perform on the server. The Fetch API provides a simple and consistent way to interact with APIs and make various types of requests in JavaScript.
Top comments (0)