axios二次封装如何写
时间: 2023-08-08 17:06:46 浏览: 58
写axios的二次封装可以根据项目需求和个人偏好进行定制化,下面是一个简单的示例来说明如何写axios的二次封装:
1. 创建一个新的JavaScript文件,命名为`axiosInstance.js`(也可以使用其他名称)。
2. 在`axiosInstance.js`文件中引入axios库和其他需要的依赖:
```javascript
import axios from 'axios';
// 其他依赖,如错误处理库、请求拦截器等
```
3. 创建一个axios实例,并进行一些配置:
```javascript
const instance = axios.create({
baseURL: 'http://api.example.com', // 设置统一的请求前缀
timeout: 5000, // 设置请求超时时间
// 其他配置项
});
```
4. 添加请求拦截器和响应拦截器,用于统一处理请求和响应:
```javascript
instance.interceptors.request.use(
(config) => {
// 在请求发送前做一些处理,如添加请求头、请求参数处理等
return config;
},
(error) => {
// 请求错误处理
return Promise.reject(error);
}
);
instance.interceptors.response.use(
(response) => {
// 在接收到响应数据后做一些处理,如对返回数据进行统一处理、错误处理等
return response.data;
},
(error) => {
// 响应错误处理
return Promise.reject(error);
}
);
```
5. 封装自定义的API,对外提供简化的请求函数:
```javascript
export const get = (url, params) => {
return instance.get(url, { params });
};
export const post = (url, data) => {
return instance.post(url, data);
};
// 其他常用的请求方法,如put、delete等
```
6. 在需要使用axios的地方,引入封装好的二次封装库,并调用封装的API进行请求:
```javascript
import { get, post } from './axiosInstance';
get('/user', { id: 1 })
.then((response) => {
// 请求成功回调处理
})
.catch((error) => {
// 请求失败回调处理
});
post('/login', { username: 'admin', password: '123456' })
.then((response) => {
// 请求成功回调处理
})
.catch((error) => {
// 请求失败回调处理
});
```
这只是一个简单的示例,实际的二次封装可能会更加复杂,根据项目需求可以添加更多的功能和处理逻辑,如请求重试、错误提示等。根据具体的业务需求来设计和实现二次封装库,提高开发效率和代码质量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)