一、基础知识
- 概念
Axios 是专注于网络数据请求的库,只负责发请求、拿数据,不能操作DOM元素。
相比于原生的 XMLHttpRequest 对象,axios 简单易用。
相比于 jQuery,axios 更加轻量化,不能操作DOM元素,只专注于网络数据请求。
2. 基础语法
// 调用 axios 方法得到的返回值是Promise对象
axios({
method: '请求的类型',
url: '请求的 URL地址'
}).then((result) =>{
// .then用来指定请求成功之后的回调函数
//形参中的result是请求成功之后的结果
})

注意:axios在请求到数据之后,在真正的数据(data)之外,套了一层壳。
<script src="./lib/axios.js"></script>
<script>
axios({
// 请求方式
method: 'GET',
// 请求的地址
url: 'http://www.liulongbin.top:3006/api/getbooks',
}).then(function (result) {
console.log(result)
console.log(result.data)
})
</script>

二、发起axios()请求
axios({
method: '请求的类型',
url: '请求的 URL地址'
// URL 中的查询参数:如果URL中有参数,如GET请求,写在params:{}中
params: {},
// 请求体参数:如果要携带请求体,如POST请求,写在data:{}中
data: {}
}).then((result) =>{
// .then用来指定请求成功之后的回调函数
//形参中的result是请求成功之后的结果
})
- 发起GET请求
1.1 写法一
<script src="./lib/axios.js"></script>
<script>
axios({
// 请求方式
method: 'GET',
// 请求的地址
url: 'http://www.liulongbin.top:3006/api/getbooks',
// URL 中的查询参数
params: {
id: 1
},
}).then(function (result) {
console.log(result)
})
</script>

1.2 写法二
<button id="btnGet">发起GET请求</button>
<script src="./lib/axios.js"></script>
<script>
document.querySelector('#btnGet').addEventListener('click', async function () {
// 解构赋值的时候,使用 : 进行重命名
// 1. 调用 axios 之后,使用 async/await 进行简化
// 2. 使用解构赋值,从 axios 封装的大对象中,把 data 属性解构出来
// 3. 把解构出来的 data 属性,使用 冒号 进行重命名,一般都重命名为 { data: res }
const { data: res } = await axios({
method: 'GET',
url: 'http://www.liulongbin.top:3006/api/getbooks'
})
console.log(res.data)
})
</script>

- 发起POST请求
2.1 写法一
<button id="btnPost">发起POST请求</button>
<script src="./lib/axios.js"></script>
<script>
document.querySelector('#btnPost').addEventListener('click', function () {
axios({
method: 'POST',
url: 'http://www.liulongbin.top:3006/api/post',
data: {
name: 'zs',
age: 20
}
}).then(function(result){
console.log(result)
})
})
</script>

2.2 写法二
<button id="btnPost">发起POST请求</button>
<script src="./lib/axios.js"></script>
<script>
document.querySelector('#btnPost').addEventListener('click', async function () {
// 如果调用某个方法的返回值是 Promise 实例,则前面可以添加 await!
// await 只能用在被 async “修饰”的方法中
const { data } = await axios({ //{ data } 解构赋值:从一个对象中选出需要的一个属性
method: 'POST',
url: 'http://www.liulongbin.top:3006/api/post',
data: {
name: 'zs',
age: 20
}
})
console.log(data)
})
</script>

三、axios直接发起请求
- 直接发起axios.get()请求
<button id="btnGET">GET</button>
<script src="./lib/axios.js"></script>
<script>
document.querySelector('#btnGET').addEventListener('click', async function () {
const { data: res } = await axios.get('http://www.liulongbin.top:3006/api/getbooks', {
params: { id: 1 }
})
console.log(res)
})
</script>

- 直接发起axios.post()请求
<button id="btnPOST">POST</button>
<script src="./lib/axios.js"></script>
<script>
document.querySelector('#btnPOST').addEventListener('click', async function () {
// axios.post('url', { /* POST 请求体数据 */ })
const { data: res } = await axios.post('http://www.liulongbin.top:3006/api/post', { name: 'zs', gender: '女' })
console.log(res)
})
</script>
