Axios用法

Axios用法详解

Posted by Starrynight on 2024-06-27
Estimated Reading Time 4 Minutes
Words 903 In Total
Viewed Times

🚀 Axios 用法详解(含常用库 + 实例)


✅ 一、Axios 是什么?

Axios 是一个基于 Promise 的 浏览器和 Node.js 的 HTTP 请求库,可以替代原生的 fetchXMLHttpRequest,更强大、更易用,支持请求拦截、响应拦截、取消请求、超时设置等功能。

安装:

1
2
3
4
5
# npm 安装
npm install axios

# 或 yarn
yarn add axios

✅ 二、基本使用方法

1
2
3
4
5
6
7
8
9
10
11
12
import axios from 'axios';

// 1. GET 请求
axios.get('/api/user')
.then(res => console.log(res.data))
.catch(err => console.error(err));

// 2. POST 请求
axios.post('/api/login', {
username: 'test',
password: '123456'
}).then(res => console.log(res.data));

✅ 三、axios 的请求配置项

1
2
3
4
5
6
7
8
9
10
axios({
url: '/api/data',
method: 'get',
params: { id: 123 }, // 用于 GET 查询参数
data: { name: 'Tom' }, // 用于 POST 请求体
headers: {
'Content-Type': 'application/json'
},
timeout: 5000 // 超时限制(单位:毫秒)
});

✅ 四、全局配置

1
2
3
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 10000;
axios.defaults.headers.common['Authorization'] = 'Bearer token';

✅ 五、创建自定义实例(推荐使用)

1
2
3
4
5
6
7
8
9
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 8000,
headers: {
'Content-Type': 'application/json'
}
});

instance.get('/users').then(res => console.log(res.data));

✅ 六、请求拦截器 & 响应拦截器(统一处理 token、错误等)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 添加请求拦截器
instance.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, error => Promise.reject(error));

// 添加响应拦截器
instance.interceptors.response.use(response => {
// 统一处理响应数据
return response.data;
}, error => {
// 统一处理错误
if (error.response?.status === 401) {
alert('请重新登录');
}
return Promise.reject(error);
});

✅ 七、常用 axios 功能补充

📌 1. 取消请求

1
2
3
4
5
6
7
8
const controller = new AbortController();

axios.get('/api/data', {
signal: controller.signal
});

// 取消请求
controller.abort();

📌 2. 并发请求(多个请求一起发)

1
2
3
4
5
6
Promise.all([
axios.get('/api/user'),
axios.get('/api/posts')
]).then(([userRes, postsRes]) => {
console.log(userRes.data, postsRes.data);
});

✅ 八、完整示例(React 中使用 axios + 封装)

🔧 1. 封装 axios 请求(request.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/utils/request.ts
import axios from 'axios';

const request = axios.create({
baseURL: '/api',
timeout: 5000
});

request.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});

request.interceptors.response.use(
res => res.data,
err => {
alert(err.response?.data?.message || '请求失败');
return Promise.reject(err);
}
);

export default request;

🔧 2. 调用接口(如用户登录)

1
2
3
4
5
6
// src/api/user.ts
import request from '@/utils/request';

export function login(data: { username: string, password: string }) {
return request.post('/login', data);
}
1
2
3
4
5
6
7
8
9
// React 组件中使用
import { useEffect } from 'react';
import { login } from '@/api/user';

useEffect(() => {
login({ username: 'admin', password: '123456' }).then(res => {
console.log('登录成功:', res);
});
}, []);

✅ 九、配合常用工具库推荐

库名 用途
qs 用于处理 GET 请求中复杂参数序列化:?a=1&b[]=2&b[]=3
axios-retry 自动重试失败请求
axios-cache-adapter 添加缓存功能
axios-mock-adapter 本地 mock 数据用于测试
1
yarn add qs axios-retry

✅ 十、Taro 项目使用 axios 的小技巧

Taro 默认使用 taro.request(),你可以用 axios 替代:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// config/index.js 中配置 baseURL
const baseUrl = 'https://api.example.com';

axios.defaults.adapter = function (config) {
return new Promise((resolve, reject) => {
Taro.request({
url: baseUrl + config.url,
method: config.method?.toUpperCase(),
data: config.data || config.params,
header: config.headers
}).then(res => {
resolve({ data: res.data, status: res.statusCode, headers: res.header });
}).catch(err => reject(err));
});
};

✅ 总结

功能 用法
基础请求 .get(), .post() 等方法
拦截器 统一处理 token、错误信息
实例封装 推荐使用 axios.create() 创建实例
并发请求 Promise.all
配合库 qsaxios-retry


如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !