The Fetch API is a modern, promise-based interface in JavaScript used for making HTTP requests. It simplifies the process of fetching resources from a server, replacing older methods like XMLHttpRequest. Fetch provides a cleaner and more readable approach for handling network requests and responses, supporting features like Promises, streaming, and async/await.
fetch(url, options) .then(response => { // Handle the response }) .catch(error => { // Handle errors });
Fetch defaults to the GET method.
Example:
fetch("https://jsonplaceholder.typicode.com/posts") .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => console.log("Data:", data)) .catch(error => console.error("Error:", error));
To send data to a server, use the POST method with the body property in the options object.
Example:
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("Response:", data)) .catch(error => console.error("Error:", error));
The fetch function accepts an options object to configure requests:
|
Description |
||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
method | HTTP method (e.g., GET, POST, PUT, DELETE). | ||||||||||
headers | Object containing request headers. | ||||||||||
body | Data to send with the request (e.g., JSON, form data). | ||||||||||
credentials | Controls whether cookies are sent with the request (include, same-origin). |
6. Handling Responses
Method | Description |
---|---|
response.text() | Returns response as plain text. |
response.json() | Parses the response as JSON. |
response.blob() | Returns response as a binary Blob. |
response.arrayBuffer() | Provides response as an ArrayBuffer. |
Method | Description |
---|---|
response.text() | Returns response as plain text. |
response.json() | Parses the response as JSON. |
response.blob() | Returns response as a binary Blob. |
response.arrayBuffer() | Provides response as an ArrayBuffer. |
Example: Fetching JSON
fetch(url, options) .then(response => { // Handle the response }) .catch(error => { // Handle errors });
Async/await simplifies handling Promises in Fetch.
Example:
fetch("https://jsonplaceholder.typicode.com/posts") .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => console.log("Data:", data)) .catch(error => console.error("Error:", error));
Unlike XMLHttpRequest, Fetch does not reject a Promise for HTTP errors. You must check the response's ok property or status code.
Example:
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("Response:", data)) .catch(error => console.error("Error:", error));
Fetch does not natively support request timeouts. You can implement a timeout using Promise.race().
Example:
fetch("https://api.example.com/data") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error:", error));
|
Fetch API |
XMLHttpRequest | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Syntax |
Promise-based, simpler, cleaner. | Callback-based, verbose. | |||||||||||||||
Requires manual handling of HTTP errors. | Built-in HTTP error handling. | ||||||||||||||||
Supports streaming responses. | Limited streaming capabilities. | ||||||||||||||||
Works with Promises, async/await. | No built-in Promise support. |
Fetch is ideal for modern web development projects.
It integrates seamlessly with Promises and async/await.
Use it when you need cleaner and more maintainable code.
The above is the detailed content of Mastering the Fetch API: Simplifying HTTP Requests in JavaScript. For more information, please follow other related articles on the PHP Chinese website!