vue3+ts封装全局request请求
时间: 2024-10-22 09:10:03 浏览: 43
在Vue3中使用TypeScript(TS)封装全局HTTP请求,你可以创建一个名为`axiosService`或类似命名的模块,利用Axios库作为底层的HTTP客户端。首先,你需要安装`axios`和`@types/axios`以便于TypeScript支持:
```bash
npm install axios @types/axios
```
然后,在项目的一个公共文件夹(如src/api)下创建一个`axios.ts`文件,内容如下:
```typescript
import axios from 'axios';
import { AxiosInstance } from 'axios';
const instance: AxiosInstance = axios.create({
baseURL: process.env.BASE_API_URL || 'http://localhost:8080', // API地址
timeout: 5000, // 请求超时时间
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('token')}`, // 如果需要的话,添加身份验证信息
},
});
instance.interceptors.request.use((config) => {
// 添加请求拦截器
return config;
}, (error) => {
// 对请求错误做处理
console.error(error);
return Promise.reject(error);
});
instance.interceptors.response.use(
(response) => {
// 处理正常响应
return response.data;
},
(error) => {
// 处理错误响应,例如错误状态码等
console.error('请求出错', error.response.data);
if (error.response.status === 401) {
// 如果是401未授权,可以尝试清除token并跳转到登录页面
localStorage.removeItem('token');
router.push('/login');
}
return Promise.reject(error);
}
);
export default instance;
```
现在,你在Vue组件中就可以通过导入这个服务来进行全局的请求了:
```typescript
import { use } from 'vue';
import axiosService from '@/api/axios';
export default function YourComponent() {
const axios = use(axiosService);
async function fetchData() {
try {
const response = await axios.get('/your-endpoint');
// 处理返回的数据
} catch (error) {
// 错误处理
}
}
return {/* ... */}
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)