J58 axios

260 阅读2分钟

一、axios类库的应用

axios官网:www.axios-js.com/docs/

1.什么是axios?

axios:一款基于promise设计模式封装的AJAX库(jq中的ajax库,没有给予promise管理)

2.安装axios:

+ 1.npm i axios          
+ 2.页面引入, 控制台输入axios
    - console.dir(axios);

3.基础语法

  • 1.axios.get([URL],[options]) options:选项

    • axios.get();
    • axios.delete();
    • axios.head();
  • 2.axios.post([URL],[data],[options]):data 通过请求主题传递给服务器内容

    • axios.post();
    • axios.put();
  • 3、options

    • 3.1 baseURL:基础的URL路径

    • 3.2 transformRequest:处理请求参数(对POST系列有作用)

    • 3.3 transformResponse:把返回的结果进行处理

    • 3.4 headers:设置请求头

    • 3.5 params:GET系列请求传递给服务器的内容(会把params中的内容拼接位x-www-form-URLencoded这种格式,基于URL问号传参传递给服务器)

    • 3.6 paramsSerializer:传递参数的序列化

    • 3.7 timeout:超时时间

    • 3.8 withCredentials:跨域请求中是否允许携带凭证

    • 3.9 responseType:预设服务器返回结果的格式,默认是JSON,支持buffer text stream document

    执行axios.xxx()都会返回一个promise实例,ajax请求成功会把实例的状态改为fulfilled,请求失败状态为rejected,并且获取的结果或者错误原因作为实例的promise的value

        axios.get("http://127.0.0.1:5500/json/data.json?_="+Math.random(),{
    headers:{
        AAA:encodeURIComponent("你好哈哈")
    },
    params:{
        //=>等价于jq中的data:会把params中的内容拼接为x-www-form-urlencoded这种格式,
        //基于URL问号传参传递给服务器
        lx:1,
        from:"WX"
    },
    //=>axios本身只有在http状态码以2开头的时候才认为是成功的,其余都认为是失败状态,
    //当然我们可以自己来设置,基于validateStatus这个来改        
    // validateStatus:function(status){
    //     return status>=200&&status<400;
    // },
    }).then(result=>{
    //result:从服务器获取的结果
    /* config:我们自己配置的选项信息
        * Data:存储的是响应主题内容
        * headers:存储响应头的信息
        * request:ajax实例
        * status:响应状态码
        * status-text:状态码的描述
        */
    //  console.log(result);
    return result.data;
    }).catch(reason=>{
    console.log(reason);
    }).then(data=>{
    //=>data:从服务器获取的响应主体内容
    console.log(data);
    })

4.post请求


axios.post("http://127.0.0.1:5500/json/data.json",{
        lx:1,
        from:"WX"
    },{
    headers:{
        AAA:encodeURIComponent("欢迎使用axios")
    },transformRequest:function(data){
        // console.log(data);//=>{lx: 1, from: "WX"}
        if(!data) return data;
        let str=``;
        for(let key in data){
            if(!data.haOwnProperty(key))break;
            str +=`&${key}=${data[key]}`;
        }
             return str.substring(1);
    }        
    }).then(result=>{    
    return result.data;
    }).catch(reason=>{
    throw new Error(reason);
    }).then(data=>{    
        console.log(data);
    });

5.get请求

axios.get("http://127.0.0.1:5500/json/data.json?_="+Math.random(),{
       headers:{
           AAA:encodeURIComponent("你好哈哈")
       },
       params:{            
           lx:1,
           from:"WX"
       },        
   }).then(result=>{ 

    console.log(result);

    console.log(result.config.validateStatus.toString());
    //=>function(e){return e>=200&&e<300}

   return result.data;
   }).catch(reason=>{
  console.log(reason);
  throw new Error(reason);
   }).then(data=>{
       //=>data:从服务器获取的响应主体内容
       console.log(data);
   }) 

二、axios配置

在使用axios之前,引入axios 我们一般都需要配置默认的配置项

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>axios默认配置</title>
</head>
<body>
<script src="node_modules/axios/dist/axios.min.js"></script>
<script>
/* 在使用axios之前,我们一般都需要配置默认的配置项 */

// 1. 基础URL,后期在发送请求的时候,url请求地址最前面的公共部分就不需要再写了
axios.defaults.baseURL='http://127.0.0.1:5500';

//2.跨域请求中允许谢等待资源凭证(例如COOKIE信息)
axios.defaults.withCredentials=true;

//3.设置请求头:post系列中,我们传递给服务器数据的格式一般以 x-www-form-urlencoded格式为主
axios.defaults.headers['Content-Type']='application/x-www-form-urlencoded';

//4.设置请求拦截器(只对post系列有用):把基于请求主题传递给服务器的内容进行拦截,把内容格式变化x-www-form-urlencoded这种格式,在传递给服务器
axios.defaults.transformRequest=function(data){
    if(!data) return data;
    let str=``;
    for(let key in data){
        if(!data.hasOwnProperty(key)) break;
        str+=`&${key}=${data[key]}`;
    }
    return str.substring(1);
};

//5.设置响应拦截器:[成功状态]把从服务器获取的结果中的响应主体信息获取到即可;[失败状态]手动把错误信息抛出异常
axios.interceptors.response.use(function(response){
  return response.data;
  },function(error){
// return Promise.reject(error);  
throw new Error(error);
})

//6.配置什么才算成功,(把promise状态改为fulfilled)
axios.defaults.validateStatus=function(status){
return status >=200&&status<400;
}

//7.Promise.all
let promise1=Promise.resolve(100);
let  promise2=Promise.resolve(200);

axios.all([promise1,promise2]).then(results=>{
    let [val1,val2]=results;
    console.log(val1,val2);//=>100 200
});

axios.all([promise1,promise2]).then(axios.spread(function(val1,val2){
    //=>axios.spread:把基于axios.all获取的结果一项项的单独获取到
    console.log(val1,val2);//=>100 200
}));

// axios.get('/json/data2.json').then(data=>{
//     console.log(data);
// }).catch(reason=>{
//     console.log(reason);
// })

// axios.post("http://127.0.0.1:5500/json/data.json",{
//         lx:1,
//         from:"WX"
//     });

</script>
</body>
</html>