1.简介
Axios 是一个开源的可以用在浏览器端和 NodeJS 的异步通信框架,她的主要作用就是实现 AJAX 异
步通信,其功能特点如下:
从浏览器中创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API [ JS中链式编程 ]
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 XSRF(跨站请求伪造)
2. 第一个Axios
新建json文件,模拟访问返回结果data.json
{
"name": "张三",
"url": "https://www.baidu.com",
"page": 1,
"address": {
"street": "毛坦厂",
"city": "六安",
"country": "中国"
}
}
测试代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>第一个Axios</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
{{info.name}}
</div>
<script>
new Vue({
el: '#app',
data: {
info: {
name: null,
url: null,
page: null,
address: {
street: null,
city: null,
country: null
}
}
},
mounted() {
//钩子函数
axios
.get('data.json')
.then(response => (this.info = response.data));
}
})
</script>
</body>
</html>
3.get请求
http://wthrcdn.etouch.cn/weather_mini?city=巢湖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>第一个vue</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
new Vue({
el: '#app',
data: {
}
})
axios({
method: "get",
url: "http://wthrcdn.etouch.cn/weather_mini?city=巢湖"
}).then(function (resp) {
alert(JSON.stringify(resp.data));
console.log(resp.data);
})
</script>
</body>
</html>
或者简写方式
axios.get("http://wthrcdn.etouch.cn/weather_mini?city=巢湖"
).then (function (resp) {
alert(JSON.stringify(resp.data));
})
4.post请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>第一个vue</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
new Vue({
el: '#app',
data: {
}
})
//2.post
axios({
method: "post",
url: "https://api.apiopen.top/api/login",
data: JSON.stringify({
account: "1299828500@qq.com",
password: "123456"
})
}).then(function (resp) {
alert(JSON.stringify(resp.data));
})
</script>
</body>
</html>
简化写法
axios.post("https://api.apiopen.top/api/login", JSON.stringify({
account: "1299828500@qq.com",
password: "123456"
})
).then(function (resp) {
alert(JSON.stringify(resp.data));
})