axios封装请求代码
时间: 2024-06-13 13:02:54 浏览: 11
Axios 是一个流行的 JavaScript 库,用于在浏览器和 Node.js 环境中发送 HTTP 请求。封装 Axios 的代码可以帮助简化 API 请求的流程,提高代码可读性和可维护性。以下是一个简单的 Axios 封装示例,使用了 ES6 模块化和 Promise:
```javascript
// 引入 Axios
import axios from 'axios';
// 创建一个 Axios 实例并设置默认配置
const service = axios.create({
baseURL: process.env.BASE_API, // API 的基础 URL
timeout: 5000, // 设置超时时间
headers: {
'Content-Type': 'application/json', // 默认请求头
},
});
// 定义错误处理函数
service.interceptors.response.use(
(response) => response.data,
(error) => {
console.error('Error:', error.message);
return Promise.reject(error);
}
);
// 封装各种类型的请求方法
export const request = async (method, url, data = {}, config = {}) => {
const mergedConfig = { ...service.defaults, ...config };
try {
if (method === 'get') {
return await service.get(url, mergedConfig);
} else if (method === 'post') {
return await service.post(url, data, mergedConfig);
} else if (method === 'put') {
return await service.put(url, data, mergedConfig);
} else if (method === 'delete') {
return await service.delete(url, { data, ...mergedConfig });
} else {
throw new Error('Invalid method');
}
} catch (error) {
// 如果你想添加错误处理逻辑,可以在catch里处理
throw error;
}
};
// 示例使用
try {
const response = await request('get', '/users');
console.log(response.data);
} catch (error) {
console.error(error);
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)