Axios 详解与使用指南
1. Axios 简介
Axios 是一个基于 Promise
的 HTTP 客户端,能够在浏览器和 Node.js 环境中运行。它提供了一种简便的方式来执行 HTTP 请求,并支持多种请求方法,如 GET
、POST
、PUT
、DELETE
等。Axios 的配置灵活,支持请求和响应拦截器、取消请求、并发请求处理等功能,使其成为现代 Web 开发中非常流行的选择。
2. Axios 特性
- 基于 Promise:Axios 完全支持
Promise
,使得异步操作更加直观,特别是在使用async/await
时。 - 支持多种请求方式:支持常见的 HTTP 请求方法,满足不同的请求需求。
- 浏览器与 Node.js 兼容:Axios 可同时在前端和后端项目中使用。
- 拦截器:提供请求和响应拦截器,允许在请求或响应到达之前进行处理。
- 自动转换 JSON 数据:自动将 JSON 数据转换为 JavaScript 对象。
- 请求取消:支持通过
CancelToken
取消请求。 - 并发请求处理:支持
axios.all
等方法,处理多个并发请求。
3. Axios 安装与引入
3.1 使用 npm 安装
npm install axios
3.2 使用 Yarn 安装
yarn add axios
3.3 在项目中引入
在 ES6 模块化的项目中使用:
import axios from 'axios';
或者在 CommonJS 模块化的项目中使用:
const axios = require('axios');
4. Axios 基本使用
4.1 GET 请求
axios.get('/api/user', {params: {ID: 12345}
})
.then(response => {console.log(response.data);
})
.catch(error => {console.error(error);
});
4.2 POST 请求
axios.post('/api/user', {firstName: 'John',lastName: 'Doe'
})
.then(response => {console.log(response.data);
})
.catch(error => {console.error(error);
});
4.3 并发请求
function getUser() {return axios.get('/api/user');
}function getProfile() {return axios.get('/api/profile');
}axios.all([getUser(), getProfile()])
.then(axios.spread((user, profile) => {console.log('User:', user.data);console.log('Profile:', profile.data);
}))
.catch(error => {console.error(error);
});
5. Axios 配置项
5.1 全局配置
Axios 提供了全局配置,允许您设置默认的请求行为。您可以通过 axios.defaults
来设置全局配置,这些配置会应用到每个请求中。
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 10000;
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.headers.post['Content-Type'] = 'application/json';
5.2 请求配置
在发送请求时,可以通过配置对象自定义请求行为。这些配置项包括但不限于以下内容:
- url:请求的 URL,默认为请求的相对路径。
- method:请求方法,如
get
、post
等,默认值为get
。 - baseURL:将自动加在
url
前面,除非url
是一个绝对 URL。 - headers:自定义请求头。
- params:GET 请求的 URL 参数,PUT、POST 请求的
data
会自动序列化为查询字符串。 - data:PUT、POST、PATCH 请求的请求体。
- timeout:请求超时设置(毫秒),如果请求超时,将触发
timeout
错误。 - responseType:返回的数据格式,如
json
、blob
、document
、arraybuffer
、text
、stream
。 - withCredentials:表示跨域请求时是否需要使用凭证,默认为
false
。
const config = {// 请求的 URLurl: '/api/user',// 请求方法method: 'get', // 可以是 'get', 'post', 'put', 'delete', 'patch', 'options', 'head'// 基础 URL,将自动加在 `url` 前面baseURL: 'https://api.example.com',// 自定义请求头headers: {'Content-Type': 'application/json','Authorization': 'Bearer token','X-Custom-Header': 'foobar'},// URL 参数params: {ID: 12345},// POST、PUT、PATCH 请求的请求体data: {firstName: 'John',lastName: 'Doe'},// 请求超时设置(毫秒)timeout: 5000, // 超时时间设置为5秒// 响应的数据类型responseType: 'json', // 选项有 'json', 'blob', 'document', 'arraybuffer', 'text', 'stream'// `transformRequest` 允许在请求数据发送到服务器之前对其进行修改// 该函数只适用于请求方法 'PUT', 'POST', 'PATCH'transformRequest: [(data, headers) => {// 对 data 进行任意转换处理data.firstName = data.firstName.toUpperCase();return JSON.stringify(data);}],// `transformResponse` 允许在响应数据传递给 then 或 catch 之前对其进行修改transformResponse: [(data) => {// 对 data 进行任意转换处理data = JSON.parse(data);data.fullName = `${data.firstName} ${data.lastName}`;return data;}],// 是否跨站点访问控制请求,默认为 falsewithCredentials: false,// 自定义参数序列化paramsSerializer: params => {return new URLSearchParams(params).toString();},// 取消请求cancelToken: new axios.CancelToken(cancel => {// 在请求的执行过程中,可调用 `cancel` 函数来取消请求// 示例:cancel('Request canceled by the user.');}),// 验证状态码是否合法,返回 true 表示合法validateStatus: status => {return status >= 200 && status < 300; // 默认的合法范围是 200-299},// 自定义处理上传进度事件onUploadProgress: progressEvent => {console.log('Upload progress:', progressEvent.loaded);},// 自定义处理下载进度事件onDownloadProgress: progressEvent => {console.log('Download progress:', progressEvent.loaded);}
};// 发送请求
axios(config).then(response => {console.log('Response:', response.data);}).catch(error => {console.error('Error:', error);});
5.3 请求与响应数据转换
在 Axios 中,可以通过配置 transformRequest
和 transformResponse
来对请求数据和响应数据进行转换。这两个配置项分别是请求前和响应后执行的数组函数,数组中的每个函数都会依次执行。
axios.post('/api/user', {firstName: 'John',lastName: 'Doe'
}, {transformRequest: [(data, headers) => {// 在发送请求前,您可以对 data 进行自定义处理data.firstName = data.firstName.toUpperCase();return JSON.stringify(data);}],transformResponse: [(data) => {// 在响应到达客户端之前,您可以对 data 进行自定义处理data = JSON.parse(data);data.fullName = `${data.firstName} ${data.lastName}`;return data;}]
})
.then(response => {console.log(response.data);
})
.catch(error => {console.error(error);
});
5.4 异步与同步请求
Axios 默认是异步请求,基于 Promise
。通过 async/await
,您可以将异步请求写成同步代码的形式:
async function getUser() {try {const response = await axios.get('/api/user');console.log(response.data);} catch (error) {console.error(error);}
}getUser();
5.5 请求取消
Axios 提供了取消请求的功能,通过 CancelToken
来实现。您可以在需要取消请求时,调用 cancel
方法。
const CancelToken = axios.CancelToken;
let cancel;axios.get('/api/user', {cancelToken: new CancelToken(function executor(c) {cancel = c;})
})
.then(response => {console.log(response.data);
})
.catch(error => {if (axios.isCancel(error)) {console.log('Request canceled', error.message);} else {console.error(error);}
});// 取消请求
cancel('Operation canceled by the user.');
6. Axios 拦截器
6.1 请求拦截器
请求拦截器可以在请求发送前对其进行处理。例如,您可以在每次请求前自动添加 token:
axios.interceptors.request.use(config => {config.headers.Authorization = 'Bearer token';return config;
}, error => {return Promise.reject(error);
});
6.2 响应拦截器
响应拦截器可以在服务器响应到达客户端前对其进行处理。例如,您可以统一处理错误信息:
axios.interceptors.response.use(response => {return response;
}, error => {if (error.response.status === 401) {console.error('未授权,请登录');}return Promise.reject(error);
});
注意:在使用拦截器时,必须确保拦截器函数有
return
。否则,拦截器处理后的结果无法传递给下一个拦截器或最终的请求/响应处理。
7. 在项目中的封装与使用
7.1 封装 Axios 实例
在大型项目中,通常会封装 Axios 实例来处理通用配置和拦截器。
import axios from 'axios';const apiClient = axios.create({baseURL: 'https://api.example.com',timeout: 10000,headers: {'Content-Type': 'application/json','Authorization': 'Bearer token'}
});// 请求拦截器
apiClient.interceptors.request.use(config => {// 在发送请求前可以做一些处理return config;
}, error => {return Promise.reject(error);
});// 响应拦截器
apiClient.interceptors.response.use(response => {// 在响应到达客户端前可以做一些处理return response.data;
}, error => {return Promise.reject(error);
});export default apiClient;
7.2 处理接口与错误
在封装的 Axios 实例中,可以定义通用的错误处理逻辑,确保应用程序中的所有 API 请求都具有一致的错误处理方式。
apiClient.interceptors.response.use(response => {return response;
}, error => {// 自定义错误处理const { status } = error.response;switch (status) {case 401:console.error('未授权,请重新登录');break;case 404:console.error('请求资源未找到');break;default:console.error('请求错误', error.message);}return Promise.reject(error);
});
7.3 基本使用
在这个基础上,可以封装常见的 API 请求方法,比如 GET、POST、PUT、DELETE 等,提供更简洁的接口。
const api = {get(url, params = {}, config = {}) {return apiClient.get(url, {params,...config});},post(url, data = {}, config = {}) {return apiClient.post(url, data, config);},put(url, data = {}, config = {}) {return apiClient.put(url, data, config);},delete(url, params = {}, config = {}) {return apiClient.delete(url, {params,...config});}
};export default api;
7.4 通用方法
const http = function(config) {return apiClient(config)
};export default http;