Axios是什么
Axios 是一个网络请求库,内部为ajax,但是封装后使用更加便捷,可以很方便的和其他框架和库结合。Axios 是基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
特性
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
安装
使用 npm:
$ npm install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
语法展示
axios.get(地址?key1=value1&key2=value2).then(function(response){},function(err){})
axios.post(地址,{key1:value1,key2:value2}).then(function(response){},function(err){})
示例
get:
<input type="button" value="get" class="get">
//用axios通过get请求获得3个笑话
document.querySelector('.get').onclick = function() {
axios.get("https://autumnfish.cn/api/joke/list?num=3").then(function(response) {
console.log(response);
}, function(err) {
console.log(err); //若错误返回错误信息
})
}
结果:
post
<input type="button" value="post" class="post">
document.querySelector(".post").onclick = function() {
axios.post("https://autumnfish.cn/api/user/reg", {
username: "jack9581"
}).then(function(response) {
console.log(response);
}, function(err) {
console.log(err);
})
}
结果:
- axios要先导入才能使用
- then方法中的回调函数会在请求成功或失败时触发
- 通过回调函数的形参可以获取响应内容或错误信息