如何将axios进行封装在一个request.js文件中将request.js文件导入到api文件夹中
时间: 2024-09-23 12:08:43 浏览: 65
将Axios封装在`request.js`文件中并导入到其他文件,可以使代码更具模块性和复用性。以下是一般的步骤:
1. **封装axios**:
创建一个名为`request.js`的文件,比如在`src/api`目录下:
```javascript
// request.js
import axios from 'axios';
const service = axios.create({
baseURL: process.env.BASE_API_URL, // API基础地址
timeout: 5000, // 请求超时时间
withCredentials: true, // 如果涉及到跨域请求,设置为true
headers: {
'Content-Type': 'application/json',
},
});
service.interceptors.request.use(
config => {
// 在发送每个请求前添加token验证(如果需要)
// 这里只是一个例子,实际应用可能会检查登录状态
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
export default {
get: (url, params) => service.get(url, { params }),
post: (url, data) => service.post(url, data),
put: (url, data) => service.put(url, data),
delete: (url, params) => service.delete(url, { params }),
};
```
2. **在其他文件中导入并使用**:
在你需要发起网络请求的地方,如`src/api/user.js`:
```javascript
import { get, post, put, delete } from '../request'; // 引入request.js
export async function fetchData() {
try {
const response = await get('/users');
// ... 对响应进行操作
} catch (error) {
console.error(error);
}
}
```
这样,所有对网络的访问都在`request.js`文件中统一管理,提高了代码的可维护性和一致性。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)