Fetch介绍和使用教程

1.Fetch简单介绍

Fetch Api是基于Promise设计的,使用异步操作且更加简洁和易于理解,可以很简洁的发起请求并处理服务器数据的一种技术

Fetch的优点

  • 基于 Promises,代码更加简洁和易读。
  • 更好的错误处理机制:只在网络错误(如无法连接服务器)时返回 catch,而非状态码错误。
  • 支持多种数据格式(JSON、文本、二进制等)。
  • 可以处理跨域请求,通过 CORS 机制配置。

fetch 的基本用法

1
2
3
4
5
6
7
8
fetch(url)
.then(response => response.json()) // 解析 JSON 数据
.then(data => console.log(data)) // 处理数据
.catch(error => console.error('Error:', error)); // 错误处理
// 参数解释:
// url:要发送请求的目标 URL
// options(可选):可以指定请求方法(GET、POST 等)、请求头、请求体等内容
// 返回值:返回一个 Promise 对象,Promise 在请求成功时返回 Response 对象,在请求失败时被拒绝

2.Fetch 使用

(1)get请求

1
2
3
4
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

返回response对象通过.json方法来解析json数据

(2)post请求

1
2
3
4
5
6
7
8
9
10
11
12
fetch('https://api.example.com/data', {
method: 'POST', // 指定请求方法
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));

设置 method 为 ‘POST’ 来发送 POST 请求,并在请求体 body 中发送 JSON 格式的数据

(3)处理响应状态

1
2
3
4
5
6
7
8
9
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));

响应状态是否成功(response.ok),如果不成功则抛出错误

(4)发送带凭据的请求

1
2
3
fetch('https://api.example.com/data', {
credentials: 'include' // 包括 cookies 在请求中
});

使用 credentials: ‘include’ 可以在跨域请求中发送 cookies

(5)使用 Request 和 Response 对象

1
2
3
4
5
6
7
const request = new Request('flowers.jpg');
fetch(request)
.then(response => response.blob())
.then(imageBlob => {
const imageObjectUrl = URL.createObjectURL(imageBlob);
img.src = imageObjectUrl;
});

创建 Request 对象来定制请求,fetch 会返回一个 Response 对象,你可以用它来获取不同类型的响应体,如 blob、text、json 等

(6)错误处理

1
2
3
4
5
6
7
8
9
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));

任何地方抛出的错误都会被 .catch() 捕获

(7)设置请求头

1
2
3
4
5
6
7
8
9
10
11
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));

通过 headers 属性为请求添加自定义的 HTTP 头信息,例如 Content-Type、Authorization 等

(8)处理非200请求状态

1
2
3
4
5
6
7
8
9
fetch('https://example.com/api')
.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('Fetch error:', error));

fetch 不会自动将 HTTP 错误状态(如 404 或 500)作为拒绝的 Promise,仍然需要检查响应状态

(9)发送表单数据

1
2
3
4
5
6
7
8
9
10
11
const formData = new FormData();
formData.append('username', 'John');
formData.append('email', '[email protected]');

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)跨域请求

1
2
3
4
fetch('server.php?query=123')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
  • 在服务器端设置 CORS(Cross-Origin Resource Sharing)
  • 在前端,可以通过 credentials 选项来指定是否发送 cookies 等凭据

2.Fetch与php使用案例

请求代码

1
2
3
4
fetch('server.php?query=123')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

php代码

1
2
3
4
5
6
7
<?php
// server.php
$queryString = $_SERVER['QUERY_STRING'];
parse_str($queryString, $params);
$responseData = array('status' => 'success', 'data' => $params);
echo json_encode($responseData);
?>

参考文献

Vue.js 菜鸟教程