The Fetch API is a built-in feature in JavaScript that is used to communicate with a server or an API. It helps us send requests to a server and receive data from it. Fetch API is commonly used in web applications to get products, users, posts, weather information, and other data.
The basic syntax of Fetch API is:
fetch("URL")
For example:
fetch("https://jsonplaceholder.typicode.com/posts")
Here, fetch() sends a request to the given URL.
When the server receives the request, it sends a response. We can handle this response using .then().
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
});
In this example, the first .then() receives the server response. The response.json() method is used to read the JSON data from the response. The second .then() receives the actual data, which is stored in the data variable.
The basic flow is:
fetch()
↓
Request
↓
Server
↓
Response
↓
response.json()
↓
Actual Data
Fetch API can also be used to send data to a server using methods such as POST, PUT, PATCH, and DELETE.
For example, a POST request can be written as:
fetch("https://example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John",
age: 25
})
});
Fetch API is very useful in modern web development because it allows JavaScript applications to communicate with backend servers and APIs without reloading the entire webpage.
In simple words, Fetch API is a way for JavaScript to send requests to a server and receive or send data.
Top comments (0)