YouTip LogoYouTip

Fetch Api

Fetch API is a modern and powerful network request tool that allows you to asynchronously request resources through JavaScript without using the traditional XMLHttpRequest object. Fetch API can concisely initiate HTTP requests and handle server responses. Fetch API is designed based on Promises, making asynchronous operations more concise and easier to understand. **Advantages of Fetch:** * Based on **Promises**, making the code more concise and readable. * Better error handling mechanism: only returns `catch` for network errors (such as inability to connect to the server), not for status code errors. * Supports multiple data formats (JSON, text, binary, etc.). * Can handle cross-origin requests, configured via the `CORS` mechanism. ### Basic Usage of fetch The syntax of fetch is quite concise, and the most basic form is: fetch(url) .then(response => response.json()) // Parse JSON data .then(data => console.log(data)) // Process data .catch(error => console.error('Error:', error)); // Error handling **Parameters:** * **url**: The target URL to send the request to. * **options** (optional): You can specify the request method (GET, POST, etc.), request headers, request body, and more. ### Return Value Returns a Promise object. The Promise returns a Response object when the request succeeds, and is rejected when the request fails. * * * ## Using Fetch **1. Basic GET Request:** ## Example fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); In this example, fetch performs a GET request by default, returning a Response object. We parse the JSON data by calling the .json() method. **2. Sending POST Requests:** ## Example fetch('https://api.example.com/data',{ method:'POST',// Specify the request method headers:{ 'Content-Type':'application/json' }, body: JSON.stringify({ key:'value' }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); Here, we send a POST request by setting method to 'POST' and send JSON-formatted data in the request body. **3. Handling Response Status:** ## Example fetch('https://api.example.com/data') .then(response =>{ if(!response.ok){ throw new Error('Network response was not ok '+ response.statusText); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); When processing the response, we first check if the response status is successful (response.ok). If not, we throw an error. **4. Sending Requests with Credentials:** ## Example fetch('https://api.example.com/data',{ credentials:'include'// Include cookies in the request }); Using credentials: 'include' allows sending cookies in cross-origin requests. **5. Using Request and Response Objects:** ## Example const request =new Request('flowers.jpg'); fetch(request) .then(response => response.blob()) .then(imageBlob =>{ const imageObjectUrl = URL.createObjectURL(imageBlob); img.src= imageObjectUrl; }); You can create a Request object to customize the request. fetch will return a Response object, which you can use to retrieve different types of response bodies such as blob, text, json, etc. **6. Error Handling:** ## Example fetch('https://api.example.com/data') .then(response =>{ if(response.ok){ return response.json(); } throw new Error('Something went wrong'); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); In a chain of calls, any error thrown will be caught by .catch(). **7. Setting Request Headers** You can add custom HTTP header information to the request via the headers property, such as Content-Type, Authorization, etc. ## Example fetch('https://example.com/api',{ method:'POST', headers:{ 'Content-Type':'application/json', 'Authorization':'Bearer your-token' }, body: JSON.stringify({ name:'John', age:30}) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); **8. Handling Non-200 Response Statuses** Fetch does not automatically treat HTTP error statuses (like 404 or 500) as rejected Promises; you still need to check the response status. ## Example fetch('https://example.com/api') .then(response =>{ if(!response.ok){// Check response status throw new Error('Network response was not ok '+ response.statusText); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Fetch error:', error)); **9. Sending Form Data** You can use the FormData object to send form data to the server: ## Example const formData =new FormData(); formData.append('username','John'); formData.append('email','john@example.com'); fetch('https://example.com/api/form',{ method:'POST', body: formData }) .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); **10. Cross-Origin Requests** If you need to make cross-origin requests, you can set up CORS (Cross-Origin Resource Sharing) on the server side. On the frontend, you can also specify whether to send cookies and other credentials using the credentials option. ## Example fetch('https://example.com/api',{ method:'GET', credentials:'include'// Allow sending cookies during cross-origin requests }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); * * * ## Fetch and PHP Using AJAX requests in PHP is no different from using AJAX in other backend languages. PHP scripts receive requests, process data, and then return responses on the server side. Client-side JavaScript code uses the Fetch API to send requests and handle responses. For example, if you have a PHP file server.php that receives a GET request and returns some data, you can use Fetch like this: ## Example fetch('server.php?query=123') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); On the PHP side, you would parse the request parameters and return a response: ## Example 'success', 'data' => $params); echo json_encode($responseData); ?> In this way, you can communicate between the client using Fetch API and the PHP backend.
← Java ConstructorDocker Rename Command β†’