Axios

426 阅读2分钟

Axios定义

Axios是前端最流行的ajax请求库

Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

特性

  • 从浏览器创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防御XSRF

安装方式

使用 npm:(项目中使用)

 $ npm install axios

使用 bower:

 $ bower install axios

使用 yarn:(项目中使用)

 $ yarn add axios

使用 jsDelivr CDN:(学习使用)

 <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

使用 unpkg CDN:(学习使用)

 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axios的基本使用

GET获取、POST添加、PUT更改、DELETE删除

 <h2>基本使用</h2>
 <button type="button">发送GET请求</button>
 <button type="button">发送POST请求</button>
 <button type="button">发送PUT请求</button>
 <button type="button">发送DELETE请求</button>
 ​
 ​
 <script type="text/javascript">
     const btns = document.querySelectorAll('button');
 ​
 //GET获取用户数据
 btns[0].onclick = function(){
     //发送AJAX请求
     axios({
         //请求类型
         method:'GET',
         //URL
         url:'',
     }).then(response => {
         console.log(response);
     });
 }
 ​
 //POST添加一篇新的文章
 btns[1].onclick = function(){
     //发送AJAX请求
     axios({
         //请求类型
         method:'POST',
         //URL
         url:'',
         //设置请求体
         data:{
             title:'rua',
             author:'爽宝'
         }
     }).then(response => {
         console.log(response);
     });
 }
 ​
 //PUT更新数据
 btns[2].onclick = function(){
     //发送AJAX请求
     axios({
         //请求类型
         method:'PUT',
         //URL
         url:'',
         //设置请求体
         data:{
             title:'WTF?',
             author:'爽宝'
         }
     }).then(response => {
         console.log(response);
     });
 }
 ​
 //DELETE删除数据
 btns[3].onclick = function(){
     //发送AJAX请求
     axios({
         //请求类型
         method:'DELETE',
         //URL
         url:''
     }).then(response => {
         console.log(response);
     });
 }
 </script>

axios的其他使用

axios的请求方式:

  1. axios(config)
  2. axios.request(config)
  3. axios.get(url [,config])
  4. axios.post(url [,data [,config]])
  5. axios.put(url [,data [,config]])
  6. axios.delete(url [,config])
  7. axios.patch(url [,data [,config]])
  8. axios.head(url [,config])
  9. axios.options(url[, config])
 <script type="text/javascript">
     const btns = document.querySelectorAll('button');
 ​
 //发送GET请求
 btns[0].onclick = function(){
     //axios()
     axios.request({
         method:'GET',
         url:''
     }).then(response => {
         console.log(response);
     });
 }
 ​
 //发送POST请求
 btns[1].onclick = function(){
     //axios()
     axios.post(
         '',//url
         {
             'body':'rua!',
             'postId':1
         }).then(response => {
         console.log(response);
     });
 }
 </script>

响应结构

一个请求的响应包含以下信息:

 // data由服务器提供的响应
 data: {},
 ​
 // status来自服务器响应的 HTTP 状态码
 status: 200,
 ​
 // statusText来自服务器响应的 HTTP 状态信息
 statusText: 'OK',
 ​
 // headers是服务器响应头
 // 所有的header名称都是小写,而且可以使用方括号语法访问
 // 例如:response.headers['content-type']
 headers: {},
 ​
 // config是axios请求的配置信息
 config: {},
 ​
 // request是生成此响应的请求
 // 在node.js中它是最后一个ClientRequest实例 (in redirects),
 // 在浏览器中则是 XMLHttpRequest 实例
 request: {}

当使用 then 时,您将接收如下响应:

 axios.get('/user/12345')
   .then(function (response) {
     console.log(response.data);
     console.log(response.status);
     console.log(response.statusText);
     console.log(response.headers);
     console.log(response.config);
   });

默认设置

 <script type="text/javascript">
     const btns = document.querySelectorAll('button');
 ​
 //默认设置
 axios.defaults.method = 'GET';//设置默认的请求类型为GET
 axios.defaults.baseURI = '协议+域名+端口';//设置基础URL
 axios.defaults.timeout = 3000;//超时3秒后无结果就取消请求
 ​
 //发送GET请求
 btns[0].onclick = function(){
     //axios()
     axios({
         url:''//只写路径和对应的url参数
     }).then(response => {
         console.log(response);
     });
 }
 </script>

拦截器

 <script type="text/javascript">
     // 设置请求拦截器      config 配置对象
     axios.interceptors.request.use(function(config) {
     // 在发送请求之前做些什么
     console.log('请求拦截器 成功');
     return config;
 }, function(error) {
     // 对请求错误做些什么
     console.log('请求拦截器 失败');
     return Promise.reject(error);
 });
 ​
 // 设置响应拦截器
 axios.interceptors.response.use(function(response) {
     // 2xx 范围内的状态码都会触发该函数。
     // 对响应数据做点什么
     console.log('响应拦截器 成功');
     return response;
 }, function(error) {
     // 超出 2xx 范围的状态码都会触发该函数。
     // 对响应错误做点什么
     console.log('响应拦截器 失败');
     return Promise.reject(error);
 });
 ​
 ​
 // 发送请求
 axios({
     method:'GET',
     url:'https://api.apiopen.top/getJoke'
 }).then(response => {
     console.log(response);  //成功回调
 }).catch(reson => {
     console.log(reson);     //失败回调
 })
 </script>

axios取消请求

 <h2>取消请求</h2>
 <button type="button">发送请求</button>
 <button type="button">取消请求</button>
 ​
 <script type="text/javascript">
     const btns = document.querySelectorAll('button');
 ​
 //2.声明全局变量
 let cancel = null;
 //发送请求
 btns[0].onclick = function(){
     //检查上一次请求是否已经完成
     if(cancel !== null){
         //取消上一次的请求
         cancel();
     }
     axios({
         method:'GET',
         url:''
         //1.添加配置对象的属性
         cancelToken:new axios.CancelToken(function(c){
         //将c的值赋值给cancel
         cancel = c;
     })
 }).then(response => {
     console.log(response);
     //将cancel指初始化
     cancel = null;
 });
 }
 ​
 //取消请求
 btns[1].onclick = function(){
     cancel();
 }
 </script>

常规案例:

 /**
  * 用手机号登录
  */
 function signin(){
     var phone = document.getElementById('phone');
     var password = document.getElementById('password');
     var oSign = document.getElementById('sign');
     
     oSign.onclick = function(){
         var datas = new FormData();
         datas.append('phone',phone.value);
         datas.append('password',password.value);
         
         axios({
             url:'/login.php',
             data:datas
         }).then(function(res){
             if(res.data.msg.phone){
                 alert(res.data.msg.phone);
             }
             if(res.data.msg.password){
                 alert(res.data.msg.password);
             }
             if(res.data.msg.error){
                 alert(res.data.msg.error);
             }
             if(res.data.ret === 200){
                 alert('登录成功!');
                 localStorage['phone'] = res.data.data.phone;
                 localStorage['token'] = res.data.data.token;
                 location.assign('index.html');
             }else if(res.data.msg.timeout){
                 alert(res.data.msg.timeout);
             }
         })
     }
 }
 ​
 ​
 signin();