Axios 是一个基于 Promise 的 HTTP 客户端,可以用在浏览器和 node.js 中。它有着良好的浏览器兼容性,支持 Promise API,拥有拦截请求和响应、转换请求和响应数据、取消请求、自动转换 JSON 数据等特性。
Axios 的中文文档提供了详细的介绍,包括安装、使用方法、API 文档等,可以帮助开发者快速上手。
Axios 安装
Axios 可以通过 npm 或者 yarn 来安装:
// npm $ npm install axios // yarn $ yarn add axios
Axios 使用
Axios API 是支持 Promise 的,可以使用 ES6 的 async/await 语法来使用 Axios:
// 发送 GET 请求 async function getData() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } // 发送 POST 请求 async function postData() { try { const response = await axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }); console.log(response); } catch (error) { console.error(error); } }
Axios API
Axios 的 API 包括:
- axios.request(config):发送请求
- axios.get(url[, config]):发送 GET 请求
- axios.delete(url[, config]):发送 DELETE 请求
- axios.head(url[, config]):发送 HEAD 请求
- axios.options(url[, config]):发送 OPTIONS 请求
- axios.post(url[, data[, config]]):发送 POST 请求
- axios.put(url[, data[, config]]):发送 PUT 请求
- axios.patch(url[, data[, config]]):发送 PATCH 请求
Axios 常见应用示例
Axios 常见应用示例包括:
- 发送并取回JSON数据:
axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
- 发送并取回图像:
axios.get('/image/logo.png', { responseType: 'arraybuffer' }) .then(function (response) { const base64 = btoa( new Uint8Array(response.data).reduce( (data, byte) => data + String.fromCharCode(byte), '', ), ); const src = 'data:;base64,' + base64; console.log(src); }) .catch(function (error) { console.log(error); });
- 发送并取回表单数据:
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
- 发送并取回多个请求:
axios.all([ axios.get('/user?ID=12345'), axios.get('/user?ID=67890') ]) .then(axios.spread(function (user1, user2) { console.log('User1', user1); console.log('User2', user2); }));
- 发送并取回多个请求:
axios.all([ axios.get('/user?ID=12345'), axios.get('/user?ID=67890') ]) .then(axios.spread(function (user1, user2) { console.log('User1', user1); console.log('User2', user2); }));
通过 Axios 的中文文档和常见应用示例,开发者可以快速上手,使用 Axios 来发送 HTTP 请求,实现对数据的操作。