zoukankan      html  css  js  c++  java
  • Vuejs-网络

    1.axios是什么

    是基于promise用于浏览器和node.js的http客户端一个js库,基于Promise这点要好好理解一下。

    2.特点

    支持浏览器和node.js
    支持promise
    能拦截请求和响应
    能转换请求和响应数据
    能取消请求
    自动转换JSON数据浏览器端
    支持防止CSRF

    3.安装

    1、 利用npm安装npm install axios --save
    2、 利用bower安装bower install axios --save
    3、 直接利用cdn引入<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    

    4.基本使用

    4.1 GET请求

    //通过给定的ID来发送请求
    axios.get('/user?ID=12345') 
     .then(function(response){   
     console.log(response);  
    })  
    .catch(function(err){    
    console.log(err);  
    });
    //以上请求也可以通过这种方式来发送
    axios.get('/user',
    {  params:{  
      ID:12345  
      }
    }) .then(function(response){ console.log(response); }) .catch(function(err){ console.log(err); });

    4.2 POST请求

    axios.post('/user',
    {
    firstName:'Fred',
    lastName:'Flintstone'
    }
    )
    .then(function(res){
    console.log(res);
    })
    .catch(function(err){
    console.log(err);
    });

    4.3 一次性并发多个请求

    function
     getUserAccount(){ 
         return axios.get('/user/12345');
    } function getUserPermissions(){ return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(),getUserPermissions()]) .then(axios.spread(function(acct,perms){ //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果 }))

    5. axios API

    改变axios的一些默认配置或请求时使用对应的配置文件,实现定制

    (1) axios(config)

    //发送一个`POST`请求
    
    axios({
        method:"POST",
        url:'/user/12345',
        data:{
            firstName:"Fred",
            lastName:"Flintstone"
        }
    });
    

    (2) axios(url[,config])

    //发送一个`GET`请求(默认的请求方式)
    axios('/user/12345');
    

    5.2 请求方式的别名,这里对所有已经支持的请求方式都提供了方便的别名

    axios.request(config);
    axios.get(url[,config]);
    axios.delete(url[,config]);
    axios.head(url[,config]);
    axios.post(url[,data[,config]]);
    axios.put(url[,data[,config]])
    axios.patch(url[,data[,config]])
    

    注意:当我们在使用别名方法的时候,url,method,data这几个参数不需要在配置中声明.前面4.1,4.2用的就是请求别名方式。

    5.3 并发请求(concurrency),即是帮助处理并发请求的辅助函数

    //iterable是一个可以迭代的参数如数组等
    axios.all(iterable)
    //callback要等到所有请求都完成才会执行
    axios.spread(callback)
    

    5.4 创建一个axios实例,可以自定义它的配置

    1) axios.create([config])

    var instance = axios.create({
      baseURL:"https://some-domain.com/api/",
      timeout:1000,
      headers: {'X-Custom-Header':'foobar'}
    });
    

    (2) 实例的方法

    注意已经定义的配置将和利用create创建的实例的配置合并

    axios#request(config)
    axios#get(url[,config])
    axios#delete(url[,config])
    axios#head(url[,config])
    axios#post(url[,data[,config]])
    axios#put(url[,data[,config]])
    axios#patch(url[,data[,config]])
    

    7 请求返回的内容

    {
      data:{},
      //服务器端返回的数据
      status:200,
      //从服务器返回的http状态文本
      statusText:'OK',
      //响应头信息
      headers: {},
      //`config`是在请求的时候的一些配置信息
      config: {}
    }
    

    获取服务端的响应信息

    axios.get('/user/12345')
      .then(function(res){   
     //res是一个自定义的参数,代表请求返回的所有内容    
    console.log(res.data);  
    console.log(res.status);  
    console.log(res.statusText);   
    console.log(res.headers);   
    console.log(res.config); 
    })

    8 默认设置

    可以设置默认配置,对所有请求都有效

    8.1  全局默认配置

    axios.defaults.baseURL = 'http://api.exmple.com';
    axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
    axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';
    

    8.2 自定义的实例默认设置

    //当创建实例的时候配置默认配置
    var instance = axios.create({   
     baseURL: 'https://api.example.com'
    });  
    //当实例创建时候修改配置
    instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
    

    8.3 配置中的有优先级

    config配置将会以优先级别来合并,顺序是lib/defauts.js中的默认配置,然后是实例中的默认配置,最后是请求中的config参数的配置,越往后等级越高,后面的会覆盖前面的例子。

    //创建一个实例的时候会使用libray目录中的默认配置
    //在这里timeout配置的值为0,来自于libray的默认值
    var instance = axios.create();
    //回覆盖掉library的默认值//现在所有的请求都要等2.5S之后才会发出instance.defaults.timeout = 2500;
    //这里的timeout回覆盖之前的2.5S变成5s
    instance.get('/longRequest',{ timeout: 5000});

    9 拦截器

    这个是重点,经常用

    添加一个请求拦截器

    axios.interceptors.request.use(function(config){	
    // 在发送请求之前做些什么	
    let pathname = location.pathname;	
    if(localStorage.getItem('token')){		
    if(pathname != '/' &&  pathname != '/login'){	
       .headers.common['token'] = localStorage.getItem('token');	
    }
    }	
    return config;
    },
    function(error){	
    // 对请求错误做些什么	
    return Promise.reject(error);
    }); 
    

    添加一个响应拦截器

    axios.interceptors.response.use(function(response ){ 
    	return response;}
    ,function(error){ 
    	if (error.response) {		
    switch (error.response.status) {			
    // 返回401,清除token信息并跳转到登录页面			
    case 401:			
    localStorage.removeItem('token');			
    router.replace({				
    path: '/login'				
    //登录成功后跳入浏览的当前页面				
    // query: {redirect: router.currentRoute.fullPath}			
    })		
    }		
    // 返回接口返回的错误信息		
    return Promise.reject(error.response.data);	
    }});
    

    9.2 取消拦截器 

    var myInterceptor = axios.interceptor.request.use(function(){/*....*/});
    axios.interceptors.request.eject(myInterceptor);
    

    9.3 给自定义的axios实例添加拦截器

    var instance = axios.create();
    instance.interceptors.request.use(function(){})
    

    10.错误处理

    axios.get('/user/12345') 
     .catch(function(error){   
     if(error.response){     
     //请求已经发出,但是服务器响应返回的状态吗不在2xx的范围内    
     console.log(error.response.data);     
     console.log(error.response.status);     
     console.log(error.response.header);  
      }else {    
      //一些错误是在设置请求的时候触发     
     console.log('Error',error.message);   
     }    
    console.log(error.config);  
    });
    

      

     

     

     

      

      

      

     

     

  • 相关阅读:
    怎么在Vue项目中使用Element组件
    vue-cli 基本使用
    C++ delete指针以后应赋值为NULL
    C++ noexcept异常说明及其使用
    Qt 设置comboBox里面的字体颜色
    Qt 获取可用串口
    Qt 寻找可用串口
    荧光显微镜简介
    荧光滤光片简介
    消色差、半复消色差、复消色差的区别
  • 原文地址:https://www.cnblogs.com/cainame/p/12096746.html
Copyright © 2011-2022 走看看