Axios是什么?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
# 特性
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
# 安装
使用 npm:
|
使用 bower:
|
使用 cdn:
|
# 案例
执行GET请求
<!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>
</head>
<body>
<div id="app">
{{text.name}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data:{
text:{}
},
mounted() {
axios.get('data.json').then(res =>{
this.text = res.data
});
},
})
</script>
</body>
</html>
执行 POST
请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
ps:你需要在VScode中先安装live-server , 不然你是无法访问到本地文件的 ! 安装live-server操作如下 : 打开终端, 输入npm install -g live-server ; 出现+ live-server@1.2.1
added 194 packages from 149 contributors in 13.215s ; 证明你已经安装成功 ; 最后输入live-server 启动服务