fetch api in js
Fetch API in JavaScript
Fetch API is a modern way of making network requests in JavaScript. It provides a global fetch() method that returns a Promise which resolves to the Response object representing the response to the request.
Syntax
fetch(resource [, options])
.then(response => { ... })
.catch(error => { ... });
resource
- The URL of the resource to request.options
(optional) - An object containing request options like headers, method, body, etc.response
- The Response object returned by the server.error
- The error object thrown if the request fails.
Fetch Request Methods
The most commonly used HTTP request methods are:
GET
- The HTTP GET method is used to retrieve data from the server.POST
- The HTTP POST method is used to submit data to the server.PUT
- The HTTP PUT method is used to update an existing resource on the server.DELETE
- The HTTP DELETE method is used to delete a resource from the server.
Example
Let's see an example of how to make a GET request using fetch API:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In the above example, we are making a GET request to the JSONPlaceholder API to fetch the first post. The .json()
method is used to parse the JSON response and convert it into a JavaScript object. The returned data is then logged to the console.
Multiple Ways to Use Fetch API
There are multiple ways to use Fetch API depending on the type of request and the data being sent. Here are some examples:
- Making a POST request with JSON data:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
- Making a PUT request with form data:
const formData = new FormData();
formData.append('title', 'foo');
formData.append('body', 'bar');
formData.append('userId', 1);
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
These are just a few examples of how Fetch API can be used in JavaScript. It provides a modern and flexible way of making network requests and can be used in place of traditional methods like XMLHttpRequest.