ts5 封装 axios
时间: 2024-08-15 19:01:34 浏览: 122
在TypeScript中,TS5(假设你是指typescript的新版本,但实际上TypeScript的版本号是由Google维护的,并非按照年份命名)封装axios是一个常见的做法,因为axios是一个流行的JavaScript库,用于发送HTTP请求。以下是基本步骤:
1. 首先,你需要安装axios库和 TypeScript 的支持。在项目目录下运行:
```bash
npm install axios typescript --save
```
或者如果使用yarn:
```bash
yarn add axios typescript
```
2. 创建一个名为`axios.ts`的文件,用于封装axios实例:
```typescript
// axios.ts
import axios from 'axios';
import { AxiosInstance } from 'axios';
export const http = axios.create({
baseURL: process.env.REACT_APP_API_URL || 'http://localhost:3000', // API基础地址
timeout: 5000, // 请求超时时间 (单位 ms)
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('token') ?? ''}`, // 如果有token,设置请求头
},
});
// 返回Promise实例
export function get(url: string): Promise<any> {
return http.get(url);
}
// 示例:添加其他常用方法如post、put等
export function post(url: string, data: any): Promise<any> {
return http.post(url, data);
}
...
```
3. 现在你可以在需要的地方导入并使用封装后的http对象:
```typescript
// 使用示例
import { get, post } from './axios';
interface ResponseData {
// 根据API返回的数据结构定义
}
async function fetchData() {
try {
const response = await get('/api/users');
const responseData: ResponseData = response.data;
console.log(responseData);
} catch (error) {
console.error(error);
}
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![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)
![](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)