1. 安装和引入
# 安装
npm install axios
# 或使用 CDN
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
// 引入
import axios from 'axios';
// 或 CommonJS
const axios = require('axios');
2. 基本使用
GET 请求
// 方式1:使用 .then()
axios.get('/api/user', {
params: { id: 12345 }
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
// 方式2:使用 async/await
async function getUser() {
try {
const response = await axios.get('/api/user', {
params: { id: 12345 }
});
console.log(response.data);
} catch (error) {
console.error(error);
}
}
POST 请求
// 发送 JSON 数据
axios.post('/api/user', {
name: '张三',
age: 30
})
.then(response => {
console.log(response.data);
});
// 发送 FormData
const formData = new FormData();
formData.append('name', '张三');
formData.append('avatar', fileInput.files[0]);
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
其他 HTTP 方法
// PUT 请求
axios.put('/api/user/123', { name: '李四' });
// DELETE 请求
axios.delete('/api/user/123');
// PATCH 请求
axios.patch('/api/user/123', { age: 31 });
3. 并发请求
// 并发多个请求
Promise.all([
axios.get('/api/user/123'),
axios.get('/api/posts')
])
.then(([userResponse, postsResponse]) => {
console.log(userResponse.data, postsResponse.data);
});
// 使用 axios.all (已弃用,建议用 Promise.all)
axios.all([
axios.get('/api/user/123'),
axios.get('/api/posts')
])
.then(axios.spread((userRes, postsRes) => {
// 处理响应
}));
4. 配置选项
请求配置
axios({
method: 'post',
url: '/api/user',
data: { name: '张三' },
// 常用配置
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
params: { id: 123 }, // URL 参数
responseType: 'json', // 响应数据类型
withCredentials: true, // 携带 cookie
// 转换函数
transformRequest: [function (data, headers) {
// 修改请求数据
return JSON.stringify(data);
}],
transformResponse: [function (data) {
// 修改响应数据
return JSON.parse(data);
}]
});
创建实例(推荐)
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
});
// 使用实例
api.get('/users');
api.post('/login', { username, password });
5. 拦截器
请求拦截器
// 添加请求拦截器
axios.interceptors.request.use(
config => {
// 在发送请求前做些什么
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
响应拦截器
// 添加响应拦截器
axios.interceptors.response.use(
response => {
// 对响应数据做点什么
return response.data; // 直接返回 data
},
error => {
// 对响应错误做点什么
if (error.response?.status === 401) {
// 未授权,跳转到登录页
window.location.href = '/login';
}
return Promise.reject(error);
}
);
6. 错误处理
axios.get('/api/user')
.then(response => {
// 成功处理
})
.catch(error => {
if (error.response) {
// 服务器返回了错误状态码
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 请求已发出,但没有收到响应
console.log(error.request);
} else {
// 设置请求时发生了错误
console.log('Error', error.message);
}
console.log(error.config);
});
7. 取消请求
// 使用 CancelToken(旧方式)
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/api/user', {
cancelToken: source.token
})
.then(response => {
console.log(response.data);
})
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('请求已取消:', thrown.message);
} else {
console.error(thrown);
}
});
// 取消请求
source.cancel('操作被用户取消');
// 新方式(推荐):使用 AbortController
const controller = new AbortController();
axios.get('/api/user', {
signal: controller.signal
})
.then(response => {
console.log(response.data);
})
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('请求已取消:', thrown.message);
}
});
// 取消请求
controller.abort();
8. 完整示例
import axios from 'axios';
// 创建 axios 实例
const api = axios.create({
baseURL: process.env.REACT_APP_API_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
});
// 请求拦截器
api.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// 响应拦截器
api.interceptors.response.use(
response => response.data,
error => {
if (error.response?.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
// API 函数
export const userApi = {
getUsers: (params) => api.get('/users', { params }),
getUserById: (id) => api.get(`/users/${id}`),
createUser: (data) => api.post('/users', data),
updateUser: (id, data) => api.put(`/users/${id}`, data),
deleteUser: (id) => api.delete(`/users/${id}`)
};
// 使用示例
async function fetchData() {
try {
const users = await userApi.getUsers({ page: 1, limit: 10 });
console.log(users);
} catch (error) {
console.error('获取用户失败:', error);
}
}
9. TypeScript 支持
interface User {
id: number;
name: string;
email: string;
}
interface ApiResponse<T> {
code: number;
message: string;
data: T;
}
// 泛型请求
const getUser = async (id: number): Promise<ApiResponse<User>> => {
const response = await axios.get<ApiResponse<User>>(`/api/user/${id}`);
return response.data;
};
这些是使用 Axios 发起 Ajax 请求的核心方法。Axios 提供了丰富的配置选项和拦截器机制,非常适合现代 Web 开发。