JavaScript - JavaScript Fetch API
The Fetch API is a modern JavaScript interface used to make network requests to servers. It is mainly used to request data from APIs or send data to a server. Fetch replaces older techniques such as XMLHttpRequest and provides a simpler and more powerful way to handle HTTP requests.
The Fetch API works using promises. When a request is made, it returns a Promise that resolves to the response from the server. Because it uses promises, it allows asynchronous operations and makes code easier to read and maintain, especially when combined with async and await.
Basic syntax of Fetch:
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log("Error:", error);
});
In this example, the fetch function sends a request to the specified URL. The server returns a response object. The response is then converted into JSON format using the json() method. After that, the data can be used in the program.
Sending data using Fetch:
Fetch can also send data to a server using methods such as POST, PUT, or DELETE.
Example:
fetch("https://example.com/api", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John",
age: 25
})
})
.then(response => response.json())
.then(data => {
console.log(data);
});
In this example, data is sent to the server using the POST method. The headers specify that the data is in JSON format, and the body contains the information being sent.
Advantages of the Fetch API include cleaner syntax, promise-based structure, better support for modern JavaScript, and easier integration with asynchronous programming. It is widely used in modern web development to communicate with REST APIs and load dynamic content on web pages.