axios(VUE主流)

axios库        http://www.axios-js.com/


axios的使用方式

第一种混入模式:

document.querySelector(".btn1").onclick = function(){

        axios.get("/axios").then(res=>{

            console.log(res.data);

        })

    }

第二种工厂模式函数:(函数写法,配置参数更丰富)

get

document.querySelector(".btn1").onclick = function(){

        axios({

            method:"get",

            url:"/axios"  

        }).then(res=>{

            console.log(res.data);

        })


    }

post(带data)

document.querySelector(".btn2").onclick = function(){

        const params = new URLSearchParams();

        params.append('name', '张三');

        params.append('age', 20);

        axios({

            method:"post",

            url:"/axiosPost",

            // data:params,

            data:JSON.stringify({name:"张三",age:21}),

            headers:{

                "content-type":"application/json"

            }

        }).then(res=>{

            console.log(res.data);

        })

    }

路由设置:


拦截器

        可以拦截所有请求 或者返还,鉴权---->头部加上鉴权信息带给后端做验证

拦截管理器

class InterceptorManager {

      constructor() {

          this.handlers = [];

      }

      use(fulfilled, rejected) {

          this.handlers.push({

              fulfilled: fulfilled,

              rejected: rejected

          });

      }


把axios放到类里面管理,同时通过函数执行

简单封装axios,加入拦截管理器网络队列


let utils = {

    extends(a,b,context){

        for(let key in b){

            if(b.hasOwnProperty(key)){

                if(typeof b[key]==='function'){

                    // 函数;

                    a[key] = b[key].bind(context);

                }else{

                    // 属性;

                    a[key] = b[key]

                }

            }

        }

    }

}

class Axios{

    constructor(){

        this.test = "一些属性";

        this.interceptors = {

            request:new InterceptorManager(),

            response:new InterceptorManager()

        }

    }

    request(config){

        // 组装队列;

        let chain = [this.xhr,undefined];

        this.interceptors.request.handles.forEach(interceptor=>{

            chain.unshift(interceptor.fulfilled,interceptor.rejected);

        })

        this.interceptors.response.handles.forEach(interceptor=>{

            chain.push(interceptor.fulfilled,interceptor.rejected);

        })

        let primose = Promise.resolve(config);

        while(chain.length>0){

            primose.then(chain.shift(),chain.shift());

        }

        return primose;

        // console.log(chain);

        // [ful1,rej1,ful2,rej2,this.xhr,undefined,ful1,rej1,ful2,rej2]

        // this.xhr(config);

    }

    xhr(config){

        return new Promise(resolve=>{

            // let xhr = new XMLHttpRequest();

            // console.log("发送请求",config);

            let xhr = new XMLHttpRequest();

            let {url="",data=null,method='get',headers={}} = config;

            xhr.open(method,url,true);

            xhr.onload = function(){

                // 对返还做包装;

                resolve(xhr.responseText);

            }

            xhr.send(data);

        })

    }

}

class InterceptorManager{

    constructor(){

        this.handles = [];

    }

    use(fulfilled,rejected){

        this.handles.push({

            fulfilled,

            rejected

        });

    }

}

// Axios.prototype['get'] = function(){

//     config.method = "get";

//     this.request(config);

// }

let methodsArr = ['get',"post","put","delete","options","head"];

methodsArr.forEach(method=>{

    Axios.prototype[method] = function(config){

        config.method = method;

        return this.request(config);

    }

})

// console.dir(Axios);

function createInstance(){

    let context = new Axios();

    let instance = context.request.bind(context);

    // 把原型里的方法混入到instance里;

    utils.extends(instance,Axios.prototype,context);

    utils.extends(instance,context);

    console.dir(instance);

    return instance

}

let axios = createInstance();

// axios

// function test(){

// }

// test();

// test['get'] = function(){};....

你可能感兴趣的:(axios(VUE主流))