fetch is a JavaScript function used to make HTTP requests (like getting or sending data) to servers from a website or application. It is part of the modern web API, built into browsers, so you don’t need to import any libraries to use it.
Think of fetch as a way for your app to "talk" to another computer (usually a server) over the internet.
For example:
- When you load a webpage, it might fetch data from a database to display.
- A weather app might fetch the current weather data from an API.
- When you submit a form, it might fetch or send that information to a server.
Why Use fetch?
- To Communicate With APIs: Websites or apps often use APIs to get data (like weather data, user profiles, or news articles).
- Efficient & Modern:
fetchis simpler and more powerful than older ways likeXMLHttpRequest(XHR). - Promises-Based: It uses promises, which makes handling asynchronous code easier and cleaner.
How to Use fetch?
Here’s the syntax:
Basic Terms:
url: The endpoint where you’re making the request.options(optional): An object to specify the request type (GET, POST, etc.), headers, body data, etc.
Using fetch with Different HTTP Methods
1. GET Request (Fetching Data):
This is used to retrieve data from a server.
Example:
2. POST Request (Sending Data):
This is used to send data to a server (e.g., submitting a form).
Example:
fetch("https://api.example.com/data", {
method: "POST", // Specify the HTTP method
headers: {
"Content-Type": "application/json", // Tell the server you're sending JSON
},
body: JSON.stringify({ name: "John", age: 30 }), // The data to send
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json(); // Parse the response
})
.then((data) => {
console.log("Data saved:", data);
})
.catch((error) => {
console.error("Error:", error);
});
3. PUT Request (Updating Data):
This is used to update existing data on a server.
Example:
fetch("https://api.example.com/data/1", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Updated Name", age: 35 }),
})
.then((response) => response.json())
.then((data) => console.log("Data updated:", data))
.catch((error) => console.error("Error:", error));
4. DELETE Request (Deleting Data):
This is used to delete data from a server.
Example:
Important Features of fetch:
-
Promise-Based:
fetchreturns a promise.- If the request succeeds, the promise is resolved.
- If it fails, the promise is rejected.
-
Response Object:
- The
responseobject contains information like status codes (200,404, etc.) and methods to read the data (json(),text(), etc.).
- The
-
Error Handling:
- If the request fails (e.g., no internet), you can catch errors using
.catch.
- If the request fails (e.g., no internet), you can catch errors using
Why Is fetch Better?
-
Modern and Flexible:
- It’s simpler and more powerful than older methods like
XMLHttpRequest.
- It’s simpler and more powerful than older methods like
-
Supports JSON Easily:
- Since most APIs use JSON, you can parse it easily with
response.json().
- Since most APIs use JSON, you can parse it easily with
-
Handles Cross-Origin Requests:
- It works with APIs that require
CORS(Cross-Origin Resource Sharing).
- It works with APIs that require
Example: Complete Flow
Let’s assume you have an API for a task manager. Here's how you could use fetch to:
- Get tasks
- Add a new task
- Delete a task