Fetch API
Fetch API is a modern, powerful network request tool that allows you to request resources asynchronously through JavaScript without using the traditional XMLHttpRequest object.
Fetch API can concisely send HTTP requests and handle server responses.
Fetch API is designed based on Promises, making asynchronous operations more concise and easier to understand.
Fetch advantages:
- Based onPromises, making the code more concise and readable.
- Better error handling mechanism: only returns on network errors (such as inability to connect to the server)
catch, rather than status code errors. - Supports multiple data formats (JSON, text, binary, etc.).
- Can handle cross-origin requests, through
CORSmechanism configuration.
Basic usage of fetch
The syntax of fetch is quite concise; the most basic form is:
fetch(url)
.then(response => response.json()) // 解析 JSON 数据
.then(data => console.log(data)) // 处理数据
.catch(error => console.error('Error:', error)); // 错误处理
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 on successful request, and is rejected on failure.
Using Fetch
1. Basic GET request:
Example
.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. The returned response is a Response object, and JSON data is parsed by calling the .json() method.
2. Sending a POST request:
Example
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
.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 handling the response, we first check whether the response status is successful (response.ok), and throw an error if it is not.
4. Sending requests with credentials:
Example
credentials: 'include' // Include cookies in the request
});
Using credentials: 'include' allows cookies to be sent in cross-origin requests.
5. Using Request and Response objects:
Example
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 returns a Response object, which you can use to obtain different types of response bodies, such as blob, text, json, etc.
6. Error handling:
Example
.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 chained call, errors thrown anywhere will be caught by .catch().
7. Setting request headers
You can add custom HTTP header information to the request using the headers property, such as Content-Type, Authorization, etc.
Example
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 (such as 404 or 500) as rejected Promises; you still need to check the response status.
Example
.then(response => {
if (!response.ok) { // Check the 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
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));
Cross-origin requests
If cross-origin requests are needed, you can set up CORS (Cross-Origin Resource Sharing) on the server side. On the front end, you can also use the credentials option to specify whether to send credentials such as cookies.
Example
method: 'GET',
credentials: 'include' // Allow cookies to be sent with 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 essentially no different from using AJAX in other backend languages. PHP scripts receive requests, process data, and return responses on the server side.
Client-side JavaScript code uses the Fetch API to send requests and process 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
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
On the PHP end, you will parse the request parameters and return a response:
Example
// server.php
$queryString = $_SERVER['QUERY_STRING'];
parse_str($queryString, $params);
$responseData = array('status' => 'success', 'data' => $params);
echo json_encode($responseData);
?>
This way, you can use the Fetch API on the client side to communicate with the PHP backend.
Other extensions