https://api.example.com // 根路径
1. 获取资源列表
描述:获取所有用户信息。
方法:GET
URL:/api/users
响应:
[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
前端调用:
javascript
fetch('https://api.example.com/api/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
axios.get('https://api.example.com/api/users')
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
- axios.get:发起一个GET请求。
- .then(response => console.log(response.data)):
- 请求成功时,response 是 Axios 返回的响应对象。
- response.data 是服务器返回的实际数据。
- .catch(error => console.error('Error:', error)):
- 请求失败时,error 是 Axios 提供的错误对象。
- error 包含了错误详情,例如网络错误、服务器返回的错误状态码等
优化错误处理
- error 是 Axios 提供的错误对象,通常包含以下属性:
- error.message:错误的描述信息。
- error.response:如果服务器返回了响应(如 4xx 或 5xx 状态码),error.response 会包含响应的详细信息。
- error.response.data:服务器返回的错误数据。
- error.response.status:HTTP 状态码(如 404、500)。
- error.response.headers:响应头。
- error.request:如果请求已发出但没有收到响应(如网络错误),error.request 会包含请求的详细信息。
优化错误处理
为了更好地处理错误,可以根据 error.response 和 error.request 区分不同类型的错误:
javascriptaxios.get('https://api.example.com/api/users') .then(response => { // 请求成功,打印数据 console.log('Data:', response.data); }) .catch(error => { if (error.response) { // 服务器返回了错误状态码 console.error('Server Error:', error.response.data); console.error('Status Code:', error.response.status); } else if (error.request) { // 请求已发出,但没有收到响应 console.error('Network Error:', error.message); } else { // 其他错误 console.error('Error:', error.message); } });
- error 是 Axios 自动传递的参数,不需要显式定义。
- error 对象包含详细的错误信息,可以通过 error.response 和 error.request 区分不同类型的错误。
- 优化错误处理:根据错误类型(服务器错误、网络错误、其他错误)分别处理,提供更清晰的调试信息。
2. 获取单个资源
描述:获取指定ID的用户信息。
方法:GET
URL:/api/users/{id}
响应:
{ "id": 1, "name": "Alice" }
前端调用:
javascript
const userId = 1;
fetch(`https://api.example.com/api/users/${userId}`)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
const userId = 1;
axios.get(`https://api.example.com/api/users/${userId}`)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
3. 创建资源
描述:创建一个新用户。
方法:POST
URL:/api/users
请求体:
{ "name": "Charlie" }
响应
{ "id": 3, "name": "Charlie" }
前端调用:
javascript
const newUser = { name: 'Charlie' };
fetch('https://api.example.com/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
const newUser = { name: 'Charlie' };
axios.post('https://api.example.com/api/users', newUser)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
4. 更新资源
描述:更新指定ID的用户信息。
方法:PUT
URL:/api/users/{id}
请求体:
{ "name": "Alice Smith" }
响应:
{ "id": 1, "name": "Alice Smith" }
前端调用:
javascript
const userId = 1;
const updatedUser = { name: 'Alice Smith' };
fetch(`https://api.example.com/api/users/${userId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedUser)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
const userId = 1;
const updatedUser = { name: 'Alice Smith' };
axios.put(`https://api.example.com/api/users/${userId}`, updatedUser)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
5. 部分更新资源
描述:部分更新指定ID的用户信息。
方法:PATCH
URL:/api/users/{id}
请求体:
{ "name": "Alice Johnson" }
响应:
{ "id": 1, "name": "Alice Johnson" }
前端调用:
javascript
const userId = 1;
const partialUpdate = { name: 'Alice Johnson' };
fetch(`https://api.example.com/api/users/${userId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(partialUpdate)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
const userId = 1;
const partialUpdate = { name: 'Alice Johnson' };
axios.patch(`https://api.example.com/api/users/${userId}`, partialUpdate)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
6. 删除资源
描述:删除指定ID的用户。
方法:DELETE
URL:/api/users/{id}
响应:204 No Content
前端调用:
javascript
const userId = 1;
fetch(`https://api.example.com/api/users/${userId}`, {
method: 'DELETE'
})
.then(response => {
if (response.status === 204) {
console.log('User deleted successfully');
}
})
.catch(error => console.error('Error:', error));
javascript
const userId = 1;
axios.delete(`https://api.example.com/api/users/${userId}`)
.then(response => {
if (response.status === 204) {
console.log('User deleted successfully');
}
})
.catch(error => console.error('Error:', error));
7. 过滤资源
描述:根据条件过滤用户列表。
方法:GET
URL:/api/users?name=Alice
响应:
[
{ "id": 1, "name": "Alice" }
]
前端调用:
javascript
const query = 'Alice';
fetch(`https://api.example.com/api/users?name=${query}`)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
const query = 'Alice';
axios.get(`https://api.example.com/api/users?name=${query}`)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
8. 分页获取资源
描述:分页获取用户列表。
方法:GET
URL:/api/users?page=1&limit=10
响应:
{
"data": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
],
"pagination": {
"page": 1,
"limit": 10,
"total": 100
}
}
前端调用:
javascript
const page = 1;
const limit = 10;
fetch(`https://api.example.com/api/users?page=${page}&limit=${limit}`)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
const page = 1;
const limit = 10;
axios.get(`https://api.example.com/api/users?page=${page}&limit=${limit}`)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
9. 嵌套资源
描述:获取指定用户的所有订单。
方法:GET
URL:/api/users/{userId}/orders
响应:
[
{ "id": 101, "product": "Laptop" },
{ "id": 102, "product": "Phone" }
]
前端调用:
javascript
const userId = 1;
fetch(`https://api.example.com/api/users/${userId}/orders`)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
const userId = 1;
axios.get(`https://api.example.com/api/users/${userId}/orders`)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
10. 搜索资源
描述:搜索用户。
方法:GET
URL:/api/users/search?q=Alice
响应:
[
{ "id": 1, "name": "Alice" }
]
前端调用:
javascript
const searchQuery = 'Alice';
fetch(`https://api.example.com/api/users/search?q=${searchQuery}`)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
const searchQuery = 'Alice';
axios.get(`https://api.example.com/api/users/search?q=${searchQuery}`)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
总结 :
(1)Fetch
- Fetch API:使用 fetch 发起HTTP请求,处理响应和错误。
- 异步处理:通过 .then() 和 .catch() 处理异步操作。
- 请求配置:
- method:指定HTTP方法(GET、POST、PUT、PATCH、DELETE)。
- headers:设置请求头,如 Content-Type。
- body:传递请求数据(JSON格式)。
- URL参数:动态拼接URL参数(如 userId、query)。
- 错误处理:捕获并处理网络错误或API返回的错误。
(2)Axios:
- 语法简洁,支持Promise。
- 自动转换JSON数据。
- 支持请求和响应拦截器。
- 提供更强大的错误处理能力。
通用配置:
- 可以设置全局默认配置,例如 baseURL:
javascriptaxios.defaults.baseURL = 'https://api.example.com';
- 可以设置请求头:
javascriptaxios.defaults.headers.common['Authorization'] = 'Bearer token';错误处理:
- 使用 .catch() 捕获错误。
- 可以通过 error.response 获取服务器返回的错误信息:
javascript.catch(error => { if (error.response) { console.error('Server Error:', error.response.data); } else { console.error('Network Error:', error.message); } });