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,加入拦截管理器网络队列

 

// 混入; 把函数及当成函数有当成对象使用;---》 axios()/axios.get()/axios.post。。。。;

// 拦截器;队列数组(函数没有执行;);--》控制执行顺序  [网络请求]  --》网络请求前unshift request 拦截器(多个InterceptorManager);  ---》网络请求后 push response  拦截器   ---》 异步执行;

// 适配器;  ---》 判断环境执行不同代码;

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()

        }

        this.adapter = new Adapter();

    }

    request(config){

        // 组装队列;

        let chain = [this.dispatchXhr.bind(this),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 =   primose.then(chain.shift(),chain.shift());

        }

        // [function fn1(){},function fn2(){}....];

        // chain.shift()====function fn1(){}

        // primose.then(function fn1(){},function fn2(){});

        return primose;

        // console.log(chain);

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

        // this.xhr(config);

    }

    dispatchXhr(config){

        // 判断环境?特殊的变量;

        if(typeof process !=='undefined'){

            // 服务端

            return this.adapter.http(config);

        }else{

            // 客户端

            return  this.adapter.xhr(config);

        }

    }

}

// 适配器:adapter  适配node端和js端;

class Adapter{

    http(config){

        // 在nodejs端发送请求的;(服务端代理)

        return new Promise((resolve, reject) => {

            const http = require("http");

            // const https = require("https")

            // http://localhost:4000/axios

            const urls = require("url");

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

            let pathObj = urls.parse(url)

            let options = {

                host: pathObj.hostname,

                port: pathObj.port,

                path: pathObj.path,

                method: config.method.toUpperCase(),

                headers: headers

            };

            // let options = {

            //     host:'localhost',

            //     port:3000,

            //     path:'/atest',

            //     method:'POST',

            //     headers:{

            //         "content-type":"application/json"

            //     }

            // }

            // console.log(options);

            let request = http.request(options, res => {

                let reslut = "";

                res.on("data", chunk => {

                    reslut += chunk;

                })

                res.on("end", () => {

                    console.log(reslut.toString())

                    resolve(JSON.parse(reslut.toString()));

                })

            })

            request.on("error", err => {

                reject(err);

            })

            request.end();

        })

        console.log("node端执行了",config);

    }

    xhr(config){

        // 客户端请求;

        return new Promise(resolve=>{

            // console.log(config)

            // 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();

if(typeof process !=='undefined'){

    // 服务端

   module.exports = axios;

}

// axios

// function test(){

// }

// test();

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

 

请求axios

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值