1. axios介绍
VUE中结合网络数据进行应用的开发
目前十分流行网络请求库,专门用来发送请求,其内部还是ajax,进行封装之后使用更加方便
axios作用: 在浏览器中可以帮助我们完成 ajax异步请求的发送.
2. axios入门
使用步骤:
2.1 导包
<!-- 官网提供的 axios 在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2.2 请求方式,以GET和POST举例
2.2.1 GET
axios.get(地址?key=value&key2=value2).then(function(response){},function(error)
{});
2.2.2 POST
axios.post(地址,{key:value,key2:value2}).then(function(response)
{},function(error){})
2.3 根据接口文档, 访问测试接口,进行测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
/*
axios总结
1.axios必须要导包
2.使用get或者post方式发送请求
3.then方法 中的回调函数,会在请求成功或者失败的时候被触发
4.通过回调函数的形参,可以获取响应的内容
*/
</style>
</head>
<body>
<input type="button" value="get请求" id="get" />
<input type="button" value="post请求" id="post" />
</body>
<script src="./js/axios.min.js"></script>
<script>
/*
随机笑话接口测试
请求地址:https://autumnfish.cn/api/joke/list
请求方法:get
请求参数:num(笑话条数,数字)
响应内容:随机笑话
*/
document.getElementById("get").onclick = function () {
axios.get("https://autumnfish.cn/api/joke/list?num=1").then(
function (resp) {
//调用成功
console.log(resp);
},
function (err) {
//调用失败
console.log(err);
}
);
};
/*
用户注册
请求地址:https://autumnfish.cn/api/user/reg
请求方法:post
请求参数:username:"用户民"
响应内容:注册成功或失败
*/
document.getElementById("post").onclick = function () {
axios
.post("https://autumnfish.cn/api/user/reg", { username: "张abc" })
.then(
function (resp) {
console.log(resp);
},
function (error) {
console.log(error);
}
);
};
</script>
</html>
axios总结
1.axios 必须导包才能使用
2.使用get或者post方法,就可以发送请求
3.then方法中的回调函数,会在请求成功或者请求失败的时候触发
4.通过回调函数的形参可以获取响应的内容,或者错误信息
节选自拉钩教育JAVA系列培训