简介
Axios是一个基于Promise网络请求库,作用于node.js和浏览器中。在服务端使用原生node.js http模块,在浏览器段使用XMLHttpRequest。
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 超时处理
- 查询参数序列化支持嵌套项处理
- 自动将请求体序列化为:
JSON(application/json)
Multipart/FormData(multipart/form-data)
URL encoded form(application/x-www-form-urlencoded)
- 将
HTMLForm转换为JSON进行请求
- 自动转换
JSON数据
- 获取浏览器和
node.js的请求进度,并提供额外的信息(速度、剩余时间)
- 为
node.js设置带宽限制
- 兼容符合规范的
FormData和Blob(包括node.js)
- 客户端支持防御
XSRF
API
axios.request(config)
axiox.get(url[, config])
axiox.delete(url[, config])
axiox.head(url[, config])
axiox.options(url[, config])
axiox.post(url[, data[, config]])
axiox.put(url[, data[, config]])
axiox.patch(url[, data[, config]])
axiox.postForm(url[, data[, config]])
axiox.putForm(url[, data[, config]])
axiox.patchForm(url[, data[, config]])
请求配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| { url: '/user', method: 'get', baseURL: 'https:
transformRequest: [function (data, headers) { return data; }],
transformResponse: [function (data) { return data; }],
headers: { 'X-Requested-With': 'XMLHttpRequest' }, params: { ID: 12345 },
paramsSerializer: function (params) { return Qs.stringify(params, { arrayFormat: 'brackets' }); },
data: { firstName: 'Fred' },
data: 'Country=Brasil&City=Belo Horizonte',
timeout: 1000,
withCredentials: false,
adapter: function (config) { },
auth: { username: 'janedoe', password: 's00pers3cret' },
responseType: 'json',
responseEncoding: 'utf8',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
onUploadProgress: function (progressEvent) { },
onDownloadProgress: function (progressEvent) { },
maxContentLength: 2000,
maxBodyLength: 2000,
validateStatus: function (status) { return status >= 200 && status < 300; },
maxRedirects: 5,
socketPath: null,
httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }),
proxy: { protocol: 'https', host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } },
cancelToken: new CancelToken(function (cancel) { }),
decompress: true }
|
默认配置
全局axios默认值
1 2 3
| axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
|
自定义实例默认值
1 2 3 4 5 6 7
| const instance = axios.create({ baseURL: 'https://api.example.com' });
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
配置的优先级
配置将会按优先级进行合并。顺序是:在lib/defaults.js中找到的库默认值,然后是实例的defaults属性,最后是请求的config参数。后面的优先级要高于前面的。
1 2 3 4 5 6 7 8 9 10 11 12
|
const instance = axios.create();
instance.defaults.timeout = 2500;
instance.get('/longRequest', { timeout: 5000 });
|
拦截器
在请求或响应被then或catch处理前拦截。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| axios.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); });
axios.interceptors.response.use(function (response) { return response; }, function (error) { return Promise.reject(error); });
|
稍后需要移除拦截器:
1 2
| const interceptor = axios.interceptors.request.use(function () { }); axios.interceptors.request.eject(interceptor);
|
错误处理
使用validateStatus配置选项,可以自定义抛出错误的HTTP code。
1 2 3 4 5
| axios.get('/user/12345', { validateStatus: function (status) { return status < 500; } });
|
使用toJSON可以获得更多关于HTTP错误的信息。
1 2 3 4
| axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); });
|
取消请求
AbortController
从v0.22.0开始,Axios支持以fetch API方式——AbortController取消请求:
1 2 3 4 5 6 7 8
| const controller = new AbortController();
axios.get('/foo/bar', { signal: controller.signal }).then(function (response) { });
controller.abort();
|
CancelToken deprecated
可以使用CancelToken.source工厂方法创建一个cancel token。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const CancelToken = axios.CancelToken; const source = CancelToken.source();
axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { } });
axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token });
source.cancel('Operation canceled by the user.');
|
也可以通过传递一个executor函数到CancelToken的构造函数来创建一个cancel token:
可以使用同一个cancel token或signal取消多个请求。
1 2 3 4 5 6 7 8 9 10 11 12
| const CancelToken = axios.CancelToken; let cancel;
axios.get('/user/12345', { cancelToken: new CancelToken(function executor (c) { cancel = c; }) });
cancel();
|
在过渡期间,可以使用这两种取消API,即使是针对同一个请求:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const controller = new AbortController();
const CancelToken = axios.CancelToken; const source = CancelToken.source();
axios.get('/user/12345', { cancelToken: source.token, signal: controller.signal }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { } });
axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token });
source.cancel('Operation canceled by the user.');
controller.abort();
|
请求体编码
默认情况下,axios将JavaScript对象序列化为JSON。 要以application/x-www-form-urlencoded格式发送数据。
浏览器
在浏览器中,可以使用URLSearchParams API。
1 2 3 4
| const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);
|
可以使用qs库编码数据:
1 2
| const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 }));
|
1 2 3 4 5 6 7 8 9
| import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options);
|
自动序列化
当请求头中的content-type是application/x-www-form-urlencoded时,Axios将自动地将普通对象序列化成urlencoded的格式。
Multipart实体请求
使用multipart/form-data类型发起POST请求
浏览器
1 2 3 4 5 6
| const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Blob([1, 2, 3])); form.append('my_file', fileInput.files[0]);
axios.post('https://example.com', form);
|
Axios会将传入数据序列化,因此使用Axios提供的API可以无需手动处理FormData的数据并实现一样的效果:
1 2 3 4 5
| axios.postForm('https://httpbin.org/post', { my_field: 'my value', my_buffer: new Blob([1, 2, 3]), my_file: fileInput.files });
|
HTML表单可以直接作为请求内容来进行传输。
Node.js
1 2 3 4 5 6 7
| import axios from 'axios';
const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Blob(['some content']));
axios.post('https://example.com', form);
|
自动序列化
从v0.27.0版本开始,当请求头中的Content-Type是multipart/form-data时,Axios支持自动地将普通对象序列化成一个FormData对象。
1 2 3 4 5 6 7 8 9 10 11 12
| import axios from 'axios';
axios.post('https://httpbin.org/post', { user: { name: 'Dmitriy' }, file: fs.createReadStream('/foo/bar.jpg') }, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({ data }) => console.log(data));
|
Axios FormData序列化支持一些特殊的结尾,以执行以下操作:
{}-通过JSON.stringify序列化数据
[]-将array-like的对象使用相同的键值来展开为单独的字段
默认情况下,展开、扩展操作将在数组和FileList对象上使用。
FormData序列化支持通过config.formSerializer:object这个参数来传递一些额外的选项,以支持一些特殊的情况:
visitor: Function-用户定义的处理函数,将递归调用以安装自定义规则将数据对象序列化为FormData对象
dots :boolean = false-使用点符号而不是括号来序列化数组和对象。
metaTokens: boolean = true-在FormData键值中添加特殊对象。后端的body-parser可能会使用此元信息自动将值解析为JSON。
indexes: null|false|true = false-控制如何添加索引到打平的array-like对象的展开键值中
null-不添加中括号(arr: 1,arr: 2,arr: 3)
false(默认值)-添加空中括号(arr[]: 1,arr[]: 2,arr[]: 3)
true-添加带有索引的中括号(arr[0]: 1,arr[1]: 2,arr[2]: 3)
Axios支持一下别名方法:postForm,putForm,patchForm,这些方法只是对应的HTTP方法,其content-type头部默认设为multipart/form-data。