Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js。它提供了一种简单的方法来发送异步 HTTP 请求到 REST 端点并处理响应。以下是 Axios 学习的详细指南:
一、Axios 的介绍
1. 定义与原理
- 定义:Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js。
- 原理:Axios 在浏览器端使用 XMLHttpRequests,在 node.js 中使用 http 模块进行通信。它封装了这些底层技术,提供了更加易用和灵活的 API。
2. 特性
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF(跨站请求伪造)
3. 浏览器支持
Axios 支持所有现代浏览器,包括 Firefox、Chrome、Safari、Opera、Edge 以及 IE8+。
二、安装 Axios
Axios 可以通过多种方式安装,包括 npm、bower、yarn 以及通过 CDN 引入。
- npm 安装:
npm install axios
- bower 安装:
bower install axios
- yarn 安装:
yarn add axios
- CDN 引入:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
三、Axios 的基本用法
1. 引入 Axios
在需要使用 Axios 的文件中,通过 import
或 require
引入 Axios。
import axios from 'axios';
// 或者
const axios = require('axios');
2. 发送 GET 请求
axios.get('/user?ID=12345')
.then(function (response) {
// 处理成功情况
console.log(response);
})
.catch(function (error) {
// 处理错误情况
console.log(error);
})
.then(function () {
// 总是会执行
});
// 或者使用 async/await
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
getUser();
3. 发送 POST 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 或者使用 async/await
async function createUser() {
try {
const response = await axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
});
console.log(response.data);
} catch (error) {
console.error(error);
}
}
createUser();
4. 发送其他类型的请求(PUT、DELETE 等)
axios.put('/user/12345', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.delete('/user/12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});