#axios

使用 axios 请求后端模型时,有一些最佳实践可以帮助你编写更健壮、可维护的代码。以下是一些常见的最佳实践:

1. 创建 API 服务层

axios 请求封装在专门的服务层中,而不是在组件中直接编写请求代码。这样可以提高代码的可复用性、可测试性并保持组件的清晰。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// api.js
import axios from 'axios';

// 创建 axios 实例
const apiClient = axios.create({
baseURL: 'https://your-api-endpoint.com',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}` // 如果需要身份验证
}
});

// 获取用户信息
export function getUserInfo(userId) {
return apiClient.get(`/users/${userId}`);
}

// 更新用户信息
export function updateUserInfo(userId, data) {
return apiClient.put(`/users/${userId}`, data);
}

// 创建用户
export function createUser(data) {
return apiClient.post('/users', data);
}

然后在 Vue 组件中使用这些 API 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// UserProfile.vue
import { getUserInfo, updateUserInfo } from './api';

export default {
data() {
return {
user: {}
};
},
mounted() {
this.fetchUserInfo(1); // 获取用户信息
},
methods: {
async fetchUserInfo(userId) {
try {
const response = await getUserInfo(userId);
this.user = response.data;
} catch (error) {
console.error('Error fetching user info:', error);
}
},
async saveUserInfo() {
try {
const response = await updateUserInfo(this.user.id, this.user);
this.user = response.data;
} catch (error) {
console.error('Error saving user info:', error);
}
}
}
};

2. 错误处理

始终为 API 请求添加错误处理,避免应用崩溃并提供用户友好的反馈。你可以使用 try/catchasync/await)或者 then/catch(Promise)来捕获错误。

示例:

1
2
3
4
5
6
7
8
try {
const response = await axios.get('/api/endpoint');
// 成功处理
} catch (error) {
console.error('API请求失败', error);
// 错误提示
this.$toast.error('请求失败,请稍后重试');
}

你还可以根据错误的类型和状态码,做出不同的响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
axios.get('/api/endpoint')
.then(response => {
// 处理响应数据
})
.catch(error => {
if (error.response) {
// 请求已发出,且服务器响应了状态码
if (error.response.status === 401) {
// 处理未授权错误
} else if (error.response.status === 500) {
// 处理服务器错误
}
} else if (error.request) {
// 请求已发出,但没有响应
console.error('没有响应');
} else {
console.error('发生了其他错误', error.message);
}
});

3. 请求拦截器和响应拦截器

使用 axios 的拦截器来处理请求和响应。请求拦截器可以在发送请求之前做一些通用处理(例如添加认证信息),响应拦截器可以统一处理错误。

请求拦截器:

1
2
3
4
5
6
7
8
9
10
11
12
13
apiClient.interceptors.request.use(
config => {
// 可以在请求头中添加认证信息或其他全局信息
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);

响应拦截器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
apiClient.interceptors.response.use(
response => {
// 可以在这里做响应的统一处理,例如根据返回的状态码做全局的处理
return response;
},
error => {
// 统一错误处理
if (error.response.status === 401) {
// 处理未授权,可能是用户需要重新登录
alert('未授权,请重新登录');
}
return Promise.reject(error);
}
);

4. 请求的参数和数据结构

确保你发送到后端的请求数据结构与后端期望的模型一致。你可以通过 axiosparams(GET 请求)或 data(POST 请求)属性来绑定数据。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
// GET 请求
axios.get('/api/users', {
params: {
page: 1,
limit: 10
}
});

// POST 请求
axios.post('/api/users', {
name: 'John Doe',
email: '[email protected]'
});

5. 全局配置和环境变量

如果有多个接口或后端环境,使用环境变量来管理不同的 API 根路径、API 密钥等。

示例:

1
2
3
4
5
6
const apiClient = axios.create({
baseURL: process.env.VUE_APP_API_BASE_URL || 'https://your-api-endpoint.com',
headers: {
'Content-Type': 'application/json'
}
});

然后在 .env 文件中设置环境变量:

1
VUE_APP_API_BASE_URL=https://dev.api.com

6. 分页和懒加载

对于数据量大的接口,建议使用分页、懒加载等技术来优化性能。通过在请求中添加分页参数,将数据分批获取,避免一次性请求大量数据。

示例:

1
2
3
4
5
6
7
8
9
10
async fetchUsers(page = 1, limit = 20) {
try {
const response = await axios.get('/api/users', {
params: { page, limit }
});
this.users = response.data;
} catch (error) {
console.error(error);
}
}

7. 缓存和重复请求防止

如果某些请求会多次发送相同的数据,可以考虑缓存请求结果,或者在发送新请求之前,检查是否已发起了相同请求。

总结

  • 封装 API 服务层:将 axios 请求抽象成服务方法,方便管理和复用。
  • 错误处理:处理请求失败的情况,显示用户友好的错误信息。
  • 请求和响应拦截器:统一处理请求和响应,尤其是认证和错误处理。
  • 避免重复请求:缓存或防止发送重复的请求。
  • 分页和懒加载:提高性能,避免一次性加载大量数据。

这样,你的 axios 请求会更加清晰、可维护,并且具有良好的扩展性。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×