1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> </style> </head> <body> <script> function Axios (config){ this.config = config this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager(), } } Axios.prototype.request = function (config){ let promise = Promise.resolve(config) const chains = [dispatchRequest, undefined] this.interceptors.request.handlers.forEach(item => { chains.unshift(item.fulfilled, item.rejected) }) this.interceptors.response.handlers.forEach(item => { chains.push(item.fulfilled, item.rejected) }) console.log(chains) while(chains.length > 0){ promise = promise.then(chains.shift(), chains.shift()) } return promise } function dispatchRequest (config){ return new Promise((resolve, reject) => { resolve({ status: 200, statusText: 'OK' }) }) } let context = new Axios({}) let axios = Axios.prototype.request.bind(context) Object.keys(context).forEach(key => { axios[key] = context[key] }) console.dir(axios) function InterceptorManager(){ this.handlers = []; } InterceptorManager.prototype.use = function (fulfilled, rejected){ this.handlers.push({ fulfilled, rejected }) }
axios.interceptors.request.use(function one (config){ console.log('请求拦截器1 成功') return config; },function one(error){ console.log('请求拦截器1 失败') return Promise.reject(error) }) axios.interceptors.request.use(function two(config){ console.log('请求拦截器2 成功') return config; },function two(error){ console.log('请求拦截器2 失败') return Promise.reject(error) }) axios.interceptors.response.use(function (response){ console.log('响应拦截器1 成功') return response; },function (error){ console.log('响应拦截器1 失败') return Promise.reject(error) }) axios.interceptors.response.use(function (response){ console.log('响应拦截器2 成功') return response; },function (error){ console.log('响应拦截器2 失败') return Promise.reject(error) }) axios({ method: "GET", url:"http://localhost:3000/posts" }).then(response => { console.log(response) }).catch(err => { console.log(err) }) </script> </body> </html>
|