Introduction to Fetch API
The Fetch API is a modern, native JavaScript API that allows you to make HTTP requests in a simple and flexible way. It provides an easier and cleaner alternative to older technologies like XMLHttpRequest. Fetch is promise-based, which means it works well with modern JavaScript features such as async/await and .then() chaining.
The Fetch API provides an easy-to-understand way of interacting with RESTful APIs, handling both simple and complex requests. It is widely supported in modern browsers and is a common tool used for web development.
Key Features of Fetch API:
-
Promise-based: Built on Promises, providing an easy and intuitive way to manage asynchronous code.
-
Supports all HTTP methods: GET, POST, PUT, DELETE, PATCH, etc.
-
No callback hell: Thanks to Promises, it avoids nested callbacks.
-
Stream support: Fetch supports streams, which makes it suitable for handling large amounts of data efficiently.
-
Improved error handling: Unlike XMLHttpRequest, the Fetch API will not reject an HTTP error status (e.g., 404 or 500). You have to handle these manually.
Installation
The Fetch API is built into modern web browsers, meaning you don’t need to install anything if you’re working in a browser environment. It’s natively available and ready to use for making HTTP requests.
However, if you’re working in a Node.js environment (where fetch is not natively supported), you can install a polyfill such as node-fetch.
1. Using npm (For Node.js environment):
If you’re working in a Node.js environment and need to use Fetch, you can install node-fetch:
npm install node-fetch
Copy after login
Copy after login
Copy after login
Then, import it into your project:
const fetch = require('node-fetch');
Copy after login
Copy after login
Copy after login
Using the Fetch API
The Fetch API provides a global fetch() function that you can use to make HTTP requests. This function returns a Promise that resolves to the Response object representing the response to the request.
Syntax
fetch(url, [options])
Copy after login
Copy after login
Parameters
-
url:
-
Type: string
-
Description: The URL to which the request is sent. This can be a full URL or a relative URL based on the base URL defined in the request.
-
options (optional):
-
Type: object
-
Description: An optional configuration object to modify the request. Some common options include:
-
method: The HTTP method (e.g., GET, POST, PUT, DELETE).
-
headers: Custom headers to include in the request (e.g., Content-Type, Authorization).
-
body: The request body (only for methods like POST or PUT).
-
mode: Controls cross-origin requests. (e.g., 'cors', 'no-cors', 'same-origin').
-
cache: Specifies how the request will interact with the cache (e.g., 'no-store', 'reload').
-
credentials: Controls cookies and authentication (e.g., 'same-origin', 'include').
Basic Fetch Request (GET)
A basic GET request with the Fetch API is straightforward. The fetch() function makes a request to the provided URL and returns a Promise that resolves with the Response object.
Example Code:
Here’s an example of a simple GET request using the Fetch API:
npm install node-fetch
Copy after login
Copy after login
Copy after login
Explanation:
-
fetch() initiates the request to the given URL.
-
.then(response => response.json()): Converts the Response object into a JavaScript object by parsing the JSON data.
-
.catch(): Catches and logs any errors, such as network errors or failed requests.
Making POST Requests with Fetch
The Fetch API also allows you to make POST requests. POST requests are typically used for sending data to a server, like submitting a form or creating a new resource.
Syntax for POST Request:
const fetch = require('node-fetch');
Copy after login
Copy after login
Copy after login
Example Code:
Here’s an example of a POST request that sends data to the server:
fetch(url, [options])
Copy after login
Copy after login
Explanation:
-
method: 'POST': Specifies that this is a POST request.
-
body: JSON.stringify(postData): Converts the data to a JSON string before sending it in the request body.
-
headers: Sets the Content-Type header to application/json to indicate that the data being sent is in JSON format.
Handling Response Data
The Response object returned by the Fetch API contains several properties and methods for interacting with the response data.
Key Properties and Methods of Response:
-
response.json(): Parses the response body as JSON.
-
response.text(): Parses the response body as a string.
-
response.blob(): Parses the response as a binary large object (useful for handling images or files).
-
response.ok: A boolean indicating if the response status code is in the range 200-299 (successful).
-
response.status: The HTTP status code of the response (e.g., 200 for success, 404 for not found).
-
response.headers: The headers returned by the server in response to the request.
Example Code:
Here’s an example of how to handle different types of response data:
npm install node-fetch
Copy after login
Copy after login
Copy after login
Explanation:
-
response.ok checks if the response was successful (status code 200-299). If not, an error is thrown.
-
response.json() is called to parse the response as a JavaScript object.
Handling Errors in Fetch
Unlike XMLHttpRequest, the Fetch API does not automatically reject an HTTP error status (e.g., 404 or 500). It only rejects if there’s a network failure or if the request is blocked. To handle errors like 404 or 500, you’ll need to check the response.ok property.
Error Handling Example:
Here’s an example of how to handle errors effectively in Fetch:
const fetch = require('node-fetch');
Copy after login
Copy after login
Copy after login
Explanation:
-
response.ok: This checks if the response status code is in the 200–299 range (indicating success).
- If the request fails (e.g., 404 or 500 error), it will throw an error with the corresponding status code.
Conclusion
The Fetch API is a powerful and modern tool for making HTTP requests in JavaScript. It provides a clean and intuitive way to work with REST APIs, and its promise-based architecture makes it easy to manage asynchronous code. With its support for all HTTP methods, error handling, and response parsing, Fetch is an essential tool for web developers.
Whether you're fetching data, submitting forms, or handling authentication, the Fetch API offers flexibility and control over your HTTP requests, making it an excellent choice for modern web applications.
The above is the detailed content of Fetch API Full Guide. For more information, please follow other related articles on the PHP Chinese website!