Fetch API
Fetch API
Fetch API is a modern, powerful network request tool that allows you to asynchronously request resources using JavaScript without needing 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 cleaner and easier to understand.
Fetch advantages:
- Based onPromises, the code is more concise and readable.
- Better error handling mechanism: only returns
catchfor network errors (such as failure to connect to the server), rather than status code errors. - Supports multiple data formats (JSON, text, binary, etc.).
- Can handle cross-domain requests through
CORSmechanism configuration.
Basic usage of fetch
The syntax of fetch is quite simple, the most basic form is:
Original prompt (Chinese, left untranslated)
fetch(url)
.then(response => response.json()) // 解析 JSON 数据
.then(data => console.log(data)) // 处理数据
.catch(error => console.error('Error:', error)); // 错误处理
Parameters:
- urlThe target URL to send the request to.
- options(Optional): Can specify the request method (GET, POST, etc.), request headers, request body, etc.
Return value
Returns a Promise object, which resolves with a Response object upon successful request and rejects upon failure.
Use Fetch
1. Basic GET request:
Instance
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 defaults to executing a GET request, and the returned response is a Response object, which is parsed into JSON data by calling the .json() method.
** 2. Sending POST requests:**
Instance
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:**
instance
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, an error is thrown.
** 4. Sending requests with credentials:**
instance
fetch
(
'https://api.example.com/data'
,
{
credentials
:
'include'
// Including cookies in the request
}
)
;
Using credentials: 'include' allows sending cookies in cross-origin requests.
** 5. Using Request and Response objects:**
instance
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 get different types of response bodies, such as blob, text, or json.
** 6. Error Handling:**
Instance
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 chained calls, any error thrown anywhere will be caught by .catch().
** 7. Setting request headers**
You can add custom HTTP header information to a request using the headers attribute, such as Content-Type, Authorization, etc.
Instance
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 status codes
fetch does not automatically reject the Promise for HTTP error statuses (such as 404 or 500); you still need to check the response status.
Instance
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:
instance
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 CORS (Cross-Origin Resource Sharing) on the server side. On the front end, you can also specify whether to send credentials like cookies using the credentials option.
Example
fetch
(
'https://example.com/api'
,
{
method
:
'GET'
,
credentials
:
'include'
// Allow cookies to be sent when making cross-origin requests
}
)
.
then
(
response
=>
response.
json
(
)
)
.
then
(
data
=>
console.
log
(
data
)
)
.
catch
(
error
=>
console.
error
(
'Error:'
,
error
)
)
;
Fetch and PHP
There is no fundamental difference between using AJAX requests in PHP and using AJAX in other backend languages. The PHP script receives the request, processes the data on the server side, and then returns a response.
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:
Instance
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 will parse the request parameters and return a response:
instance
'success', 'data' => $params); echo json_encode($responseData); ?>This way, you can communicate with the PHP backend using the Fetch API on the client side.