axios

axios是一个专注于网络请求的库!

axios 的基本使用

1.发起GET请求

1
2
3
4
5
6
7
8
9
10
11
12
axios({
//请求方式
method:'GET',
//请求地址
url:'http://www.xxx.com',
//url中的查询参数(GET)
params:{
id:1
},
}).then(function(result){
console.log(result);
})

2.发起POST请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<body>
<button id="btnPost">发起POST请求</button>
</body>
<script>
document.querySelector('#btnPost').addEventListener('click',async function(){
//如果调用某个方法返回值是Promise实例,则前面可以添加await
//await 只能用在被async "修饰"的方法中
const {data}=await axios({
method:'POST',
url:'http://www.liulongbin.top:3006/api/post',
data:{
name:'zs',
age:20
},
})
console.log(data);
})

3.axios.get 和axios.post

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<body>
<button id="btnGET">GET</button>
<button id="btnPOST">POST</button>
</body>
<script>
(axios.get的写法)
document.querySelector('#btnGET').addEventListener('click',async function(){
/* axios.get('url地址',{
//GET参数
params:{}
}) */
const {data:res} =await axios.get('http://www.liulongbin.top:3006/api/getbooks',{
params:{id:1}
})
console.log(res);
})
(axios.post的写法)
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>