axios
基于 Promise 的 HTTP 客户端,用于浏览器和 Node.js
目录(Table of Contents)
- 功能(Features)
- 浏览器支持(Browser Support)
-
安装(Installing)
- 包管理器
- CDN
- 示例(Example)
- Axios API
- 请求方法别名(Request method aliases)
- 并发(Concurrency 👎)
- 创建实例(Creating an instance)
- 实例方法(Instance methods)
- 请求配置(Request Config)
- 响应结构(Response Schema)
-
默认配置(Config Defaults)
- 全局 axios 默认配置
- 自定义实例默认配置
- 配置优先级顺序
-
拦截器(Interceptors)
- 多个拦截器
- 错误处理(Handling Errors)
- 超时处理(Handling Timeouts)
-
取消请求(Cancellation)
- AbortController
- CancelToken 👎
-
使用
application/x-www-form-urlencoded格式- URLSearchParams
- Query string
- 🆕 自动序列化
-
使用
multipart/form-data格式- FormData
- 🆕 自动序列化
- 文件上传(Files Posting)
- HTML 表单提交(HTML Form Posting)
- 🆕 进度捕获(Progress capturing)
- 🆕 限速(Rate limiting)
- 🆕 AxiosHeaders
-
🔥 Fetch 适配器
-
🔥 自定义 fetch
- 🔥 与 Tauri 一起使用
- 🔥 与 SvelteKit 一起使用
-
- 🔥 HTTP2
- 语义化版本(Semver)
- Promises
- TypeScript
- 资源(Resources)
- 致谢(Credits)
- 许可证(License)
功能(Features)
- 浏览器请求:可直接在浏览器中发起 XMLHttpRequests 请求
- Node.js 请求:可在 Node.js 环境中发起 http 请求
- 基于 Promise:完全支持 Promise API,便于编写异步代码
- 拦截器:可拦截请求和响应,添加自定义逻辑或转换数据
- 数据转换:自动转换请求和响应数据
- 请求取消:内置请求取消机制
- 自动 JSON 处理:自动序列化和解析 JSON 数据
- 表单序列化:🆕 自动将数据对象序列化为
multipart/form-data或x-www-form-urlencoded - XSRF 防护:提供客户端防跨站请求伪造支持 ([GitHub][1])
浏览器支持(Browser Support)
| Chrome | Firefox | Safari | Opera | Edge |
|---|---|---|---|---|
| 最新 ✔ | 最新 ✔ | 最新 ✔ | 最新 ✔ | 最新 ✔ |
安装(Installing)
使用包管理器(Package manager)
使用 npm:
npm install axios
使用 bower:
bower install axios
使用 yarn:
yarn add axios
使用 pnpm:
pnpm add axios
使用 bun:
bun add axios
安装完成后,你可以通过 import 或 require 引入:
import axios, {isCancel, AxiosError} from 'axios';
你也可以使用默认导出:
import axios from 'axios';
console.log(axios.isCancel('something'));
使用 require 时,仅支持默认导出:
const axios = require('axios');
console.log(axios.isCancel('something'));
对于某些 bundler 或 ES6 lint 工具,可能需要:
import { default as axios } from 'axios';
默认配置(Config Defaults)
你可以指定默认配置,它会应用到每个请求。
全局默认配置(Global axios defaults)
axios.defaults.baseURL = 'https://api.example.com';
// 注意:如果 axios 用于多个域名,该 AUTH_TOKEN 会发送到所有域
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
自定义实例默认配置(Custom instance defaults)
const instance = axios.create({
URLSearchParams
默认情况下,axios 会将 JavaScript 对象序列化为 JSON。
如果你想使用 application/x-www-form-urlencoded:
const params = new URLSearchParams({ foo: 'bar' });
params.append('extraparam', 'value');
axios.post('/foo', params);
Query string(旧浏览器)
可以使用 qs 库:
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
或 ES6:
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
};
使用 multipart/form-data
FormData
const formData = new FormData();
formData.append('foo', 'bar');
axios.post('https://httpbin.org/post', formData);
Node.js 示例:
const FormData = require('form-data');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form);
🆕 自动序列化为 FormData
从 v0.27.0 开始,如果 Content-Type 为 multipart/form-data,axios 会自动将对象序列化为 FormData。
文件上传(Files Posting)
await axios.postForm('https://httpbin.org/post', {
'myVar': 'foo',
'file': document.querySelector('#fileInput').files[0]
});
多文件上传:
await axios.postForm('https://httpbin.org/post', {
'files[]': document.querySelector('#fileInput').files
});
HTML 表单提交(HTML Form Posting)
await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
也可以作为 JSON 发送:
await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
headers: {
'Content-Type': 'application/json'
}
});
🆕 进度捕获(Progress capturing)
const {data, headers, status} = await axios.post('https://httpbin.org/post', form, {
httpVersion: 2,
http2Options: {},
onUploadProgress(e) {
console.log('upload progress', e);
},
onDownloadProgress(e) {
console.log('download progress', e);
},
responseType: 'arraybuffer'
});
Promises
axios 依赖原生 ES6 Promise,如果环境不支持,需要 polyfill。
TypeScript
axios 内置 TypeScript 类型定义:
let user: User = null;
try {
const { data } = await axios.get('/user?ID=12345');
user = data.userDetails;
} catch (error) {
if (axios.isAxiosError(error)) {
handleAxiosError(error);
} else {
handleUnexpectedError(error);
}
}
致谢(Credits)
axios 深受 AngularJS 的 $http 服务启发,本质目标是提供一个可在 Angular 之外使用的 $http 类库。
许可证(License)
MIT
参考资料
- axios
- 参考资料
