自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

手寫Axios核心原理,再也不怕面試官問(wèn)我Axios原理

開發(fā) 前端
Axios 是一個(gè)基于 promise 的 HTTP 庫(kù),可以用在瀏覽器和 node.js 中。axios可以用在瀏覽器和 node.js 中是因?yàn)?,它?huì)自動(dòng)判斷當(dāng)前環(huán)境是什么,如果是瀏覽器,就會(huì)基于XMLHttpRequests實(shí)現(xiàn)axios。

 手寫axios核心原理

  • 手寫axios核心原理,再也不怕面試官問(wèn)我axios原理
  • 手寫axios核心原理

一、axios簡(jiǎn)介

  • axios是什么?
  • axios有什么特性?(不得不說(shuō)面試被問(wèn)到幾次)

二、基本使用方式

三、實(shí)現(xiàn)axios和axios.method

四、請(qǐng)求和響應(yīng)攔截器

  • 首先
  • 接下來(lái),再執(zhí)行
  • 接下來(lái),再執(zhí)行

 

一、axios簡(jiǎn)介
axios是什么?
Axios 是一個(gè)基于 promise 的 HTTP 庫(kù),可以用在瀏覽器和 node.js 中。

axios有什么特性?(不得不說(shuō)面試被問(wèn)到幾次)

  • 從瀏覽器中創(chuàng)建 XMLHttpRequests從 node.js
  • 創(chuàng)建 http 請(qǐng)求
  • 支持 Promise API
  • 攔截請(qǐng)求和響應(yīng)轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
  • 取消請(qǐng)求
  • 自動(dòng)轉(zhuǎn)換JSON 數(shù)據(jù)
  • 客戶端支持防御 XSRF

實(shí)際上,axios可以用在瀏覽器和 node.js 中是因?yàn)椋鼤?huì)自動(dòng)判斷當(dāng)前環(huán)境是什么,如果是瀏覽器,就會(huì)基于XMLHttpRequests實(shí)現(xiàn)axios。如果是node.js環(huán)境,就會(huì)基于node內(nèi)置核心模塊http實(shí)現(xiàn)axios簡(jiǎn)單來(lái)說(shuō),axios的基本原理就是

  1. axios還是屬于 XMLHttpRequest, 因此需要實(shí)現(xiàn)一個(gè)ajax。或者基于http 。
  2. 還需要一個(gè)promise對(duì)象來(lái)對(duì)結(jié)果進(jìn)行處理。

有什么不理解的或者是建議歡迎評(píng)論提出.項(xiàng)目已經(jīng)放到github.可以的話給個(gè)star吧!謝謝 github:https://github.com/Sunny-lucking/howToBuildMyAxios

二、基本使用方式
axios基本使用方式主要有

  1. axios(config)
  2. axios.method(url, data , config)
  1. // index.html文件 
  2. <html> 
  3. <script type="text/javascript" src="./myaxios.js"></script> 
  4. <body> 
  5. <button class="btn">點(diǎn)我發(fā)送請(qǐng)求</button> 
  6. <script> 
  7.     document.querySelector('.btn').onclick = function() { 
  8.         // 分別使用以下方法調(diào)用,查看myaxios的效果 
  9.         axios.post('/postAxios', { 
  10.           name'小美post' 
  11.         }).then(res => { 
  12.           console.log('postAxios 成功響應(yīng)', res); 
  13.         }) 
  14.  
  15.         axios({ 
  16.           method: 'post'
  17.           url: '/getAxios' 
  18.         }).then(res => { 
  19.           console.log('getAxios 成功響應(yīng)', res); 
  20.         }) 
  21.     } 
  22. </script> 
  23. </body> 
  24. </html> 
  25. </html> 

三、實(shí)現(xiàn)axios和axios.method
從axios(config)的使用上可以看出導(dǎo)出的axios是一個(gè)方法。從axios.method(url, data , config)的使用可以看出導(dǎo)出的axios上或者原型上掛有g(shù)et,post等方法。

實(shí)際上導(dǎo)出的axios就是一個(gè)Axios類中的一個(gè)方法。

如代碼所以,核心代碼是request。我們把request導(dǎo)出,就可以使用axios(config)這種形式來(lái)調(diào)用axios了。

  1. class Axios { 
  2.     constructor() { 
  3.  
  4.     } 
  5.  
  6.     request(config) { 
  7.         return new Promise(resolve => { 
  8.             const {url = '', method = 'get', data = {}} = config; 
  9.             // 發(fā)送ajax請(qǐng)求 
  10.             const xhr = new XMLHttpRequest(); 
  11.             xhr.open(method, url, true); 
  12.             xhr.onload = function() { 
  13.                 console.log(xhr.responseText) 
  14.                 resolve(xhr.responseText); 
  15.             } 
  16.             xhr.send(data); 
  17.         }) 
  18.     } 

怎么導(dǎo)出呢?十分簡(jiǎn)單,new Axios,獲得axios實(shí)例,再獲得實(shí)例上的request方法就好了。

  1. // 最終導(dǎo)出axios的方法,即實(shí)例的request方法 
  2. function CreateAxiosFn() { 
  3.     let axios = new Axios(); 
  4.     let req = axios.request.bind(axios); 
  5.     return req; 
  1. // 得到最后的全局變量axios 
  2. let axios = CreateAxiosFn(); 

點(diǎn)擊查看此時(shí)的myAxios.js

現(xiàn)在axios實(shí)際上就是request方法。

你可能會(huì)很疑惑,因?yàn)槲耶?dāng)初看源碼的時(shí)候也很疑惑:干嘛不直接寫個(gè)request方法,然后導(dǎo)出呢?非得這樣繞這么大的彎子。別急。后面慢慢就會(huì)講到。

現(xiàn)在一個(gè)簡(jiǎn)單的axios就完成了,我們來(lái)引入myAxios.js文件并測(cè)試一下可以使用不?

簡(jiǎn)單的搭建服務(wù)器:

  1. //server.js 
  2. var express = require('express'); 
  3. var app = express(); 
  4.  
  5. //設(shè)置允許跨域訪問(wèn)該服務(wù). 
  6. app.all('*'function (req, res, next) { 
  7.     res.header('Access-Control-Allow-Origin''*'); 
  8.     res.header('Access-Control-Allow-Headers''Content-Type'); 
  9.     res.header('Access-Control-Allow-Methods''*'); 
  10.     res.header('Content-Type''application/json;charset=utf-8'); 
  11.     next(); 
  12. }); 
  13.  
  14. app.get('/getTest'function(request, response){ 
  15.     data = { 
  16.         'FrontEnd':'前端'
  17.         'Sunny':'陽(yáng)光' 
  18.     }; 
  19.     response.json(data); 
  20. }); 
  21. var server = app.listen(5000, function(){ 
  22.     console.log("服務(wù)器啟動(dòng)"); 
  23. }); 
  1. //index.html 
  2. <script type="text/javascript" src="./myAxios.js"></script> 
  3.  
  4. <body> 
  5. <button class="btn">點(diǎn)我發(fā)送請(qǐng)求</button> 
  6. <script> 
  7.     document.querySelector('.btn').onclick = function() { 
  8.         // 分別使用以下方法調(diào)用,查看myaxios的效果 
  9.         axios({ 
  10.           method: 'get'
  11.           url: 'http://localhost:5000/getTest' 
  12.         }).then(res => { 
  13.           console.log('getAxios 成功響應(yīng)', res); 
  14.         }) 
  15.     } 
  16. </script> 
  17. </body> 

點(diǎn)擊按鈕,看看是否能成功獲得數(shù)據(jù)。

發(fā)現(xiàn)確實(shí)成功。

可喜可賀

現(xiàn)在我們來(lái)實(shí)現(xiàn)下axios.method()的形式。

思路:我們可以再Axios.prototype添加這些方法。而這些方法內(nèi)部調(diào)用request方法即可,如代碼所示:

  1. // 定義get,post...方法,掛在到Axios原型上 
  2. const methodsArr = ['get''delete''head''options''put''patch''post']; 
  3. methodsArr.forEach(met => { 
  4.     Axios.prototype[met] = function() { 
  5.         console.log('執(zhí)行'+met+'方法'); 
  6.         // 處理單個(gè)方法 
  7.         if (['get''delete''head''options'].includes(met)) { // 2個(gè)參數(shù)(url[, config]) 
  8.             return this.request({ 
  9.                 method: met, 
  10.                 url: arguments[0], 
  11.                 ...arguments[1] || {} 
  12.             }) 
  13.         } else { // 3個(gè)參數(shù)(url[,data[,config]]) 
  14.             return this.request({ 
  15.                 method: met, 
  16.                 url: arguments[0], 
  17.                 data: arguments[1] || {}, 
  18.                 ...arguments[2] || {} 
  19.             }) 
  20.         } 
  21.  
  22.     } 
  23. }) 

我們通過(guò)遍歷methodsArr數(shù)組,依次在Axios.prototype添加對(duì)應(yīng)的方法,注意的是'get', 'delete', 'head', 'options'這些方法只接受兩個(gè)參數(shù)。而其他的可接受三個(gè)參數(shù),想一下也知道,get不把參數(shù)放body的。

但是,你有沒(méi)有發(fā)現(xiàn),我們只是在Axios的prototype上添加對(duì)應(yīng)的方法,我們導(dǎo)出去的可是request方法啊,那怎么辦?簡(jiǎn)單,把Axios.prototype上的方法搬運(yùn)到request上即可。

我們先來(lái)實(shí)現(xiàn)一個(gè)工具方法,實(shí)現(xiàn)將b的方法混入a;

  1. const utils = { 
  2.   extend(a,b, context) { 
  3.     for(let key in b) { 
  4.       if (b.hasOwnProperty(key)) { 
  5.         if (typeof b[key] === 'function') { 
  6.           a[key] = b[key].bind(context); 
  7.         } else { 
  8.           a[key] = b[key
  9.         } 
  10.       } 
  11.        
  12.     } 
  13.   } 

然后我們就可以利用這個(gè)方法將Axios.prototype上的方法搬運(yùn)到request上啦。

我們修改一下之前的CreateAxiosFn方法即可

  1. function CreateAxiosFn() { 
  2.   let axios = new Axios(); 
  3.    
  4.   let req = axios.request.bind(axios); 
  5.   增加代碼 
  6.   utils.extend(req, Axios.prototype, axios) 
  7.    
  8.   return req; 

點(diǎn)擊查看此時(shí)的myAxios.js

現(xiàn)在來(lái)測(cè)試一下能不能使用axios.get()這種形式調(diào)用axios。

  1. <body> 
  2. <button class="btn">點(diǎn)我發(fā)送請(qǐng)求</button> 
  3. <script> 
  4.     document.querySelector('.btn').onclick = function() { 
  5.  
  6.         axios.get('http://localhost:5000/getTest'
  7.             .then(res => { 
  8.                  console.log('getAxios 成功響應(yīng)', res); 
  9.             }) 
  10.  
  11.     } 
  12. </script> 
  13. </body> 

又是意料之中成功。再完成下一個(gè)功能之前,先給上目前myAxios.js的完整代碼

  1. class Axios { 
  2.     constructor() { 
  3.  
  4.     } 
  5.  
  6.     request(config) { 
  7.         return new Promise(resolve => { 
  8.             const {url = '', method = 'get', data = {}} = config; 
  9.             // 發(fā)送ajax請(qǐng)求 
  10.             console.log(config); 
  11.             const xhr = new XMLHttpRequest(); 
  12.             xhr.open(method, url, true); 
  13.             xhr.onload = function() { 
  14.                 console.log(xhr.responseText) 
  15.                 resolve(xhr.responseText); 
  16.             } 
  17.             xhr.send(data); 
  18.         }) 
  19.     } 
  20.  
  21. // 定義get,post...方法,掛在到Axios原型上 
  22. const methodsArr = ['get''delete''head''options''put''patch''post']; 
  23. methodsArr.forEach(met => { 
  24.     Axios.prototype[met] = function() { 
  25.         console.log('執(zhí)行'+met+'方法'); 
  26.         // 處理單個(gè)方法 
  27.         if (['get''delete''head''options'].includes(met)) { // 2個(gè)參數(shù)(url[, config]) 
  28.             return this.request({ 
  29.                 method: met, 
  30.                 url: arguments[0], 
  31.                 ...arguments[1] || {} 
  32.             }) 
  33.         } else { // 3個(gè)參數(shù)(url[,data[,config]]) 
  34.             return this.request({ 
  35.                 method: met, 
  36.                 url: arguments[0], 
  37.                 data: arguments[1] || {}, 
  38.                 ...arguments[2] || {} 
  39.             }) 
  40.         } 
  41.  
  42.     } 
  43. }) 
  44.  
  45.  
  46. // 工具方法,實(shí)現(xiàn)b的方法或?qū)傩曰烊隺; 
  47. // 方法也要混入進(jìn)去 
  48. const utils = { 
  49.   extend(a,b, context) { 
  50.     for(let key in b) { 
  51.       if (b.hasOwnProperty(key)) { 
  52.         if (typeof b[key] === 'function') { 
  53.           a[key] = b[key].bind(context); 
  54.         } else { 
  55.           a[key] = b[key
  56.         } 
  57.       } 
  58.        
  59.     } 
  60.   } 
  61.  
  62.  
  63. // 最終導(dǎo)出axios的方法-》即實(shí)例的request方法 
  64. function CreateAxiosFn() { 
  65.     let axios = new Axios(); 
  66.  
  67.     let req = axios.request.bind(axios); 
  68.     // 混入方法, 處理axios的request方法,使之擁有g(shù)et,post...方法 
  69.     utils.extend(req, Axios.prototype, axios) 
  70.     return req; 
  71.  
  72. // 得到最后的全局變量axios 
  73. let axios = CreateAxiosFn(); 

四、請(qǐng)求和響應(yīng)攔截器
我們先看下攔截器的使用

  1. // 添加請(qǐng)求攔截器 
  2. axios.interceptors.request.use(function (config) { 
  3.     // 在發(fā)送請(qǐng)求之前做些什么 
  4.     return config; 
  5.   }, function (error) { 
  6.     // 對(duì)請(qǐng)求錯(cuò)誤做些什么 
  7.     return Promise.reject(error); 
  8.   }); 
  9.  
  10. // 添加響應(yīng)攔截器 
  11. axios.interceptors.response.use(function (response) { 
  12.     // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么 
  13.     return response; 
  14.   }, function (error) { 
  15.     // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么 
  16.     return Promise.reject(error); 
  17.   }); 

攔截器是什么意思呢?其實(shí)就是在我們發(fā)送一個(gè)請(qǐng)求的時(shí)候會(huì)先執(zhí)行請(qǐng)求攔截器的代碼,然后再真正地執(zhí)行我們發(fā)送的請(qǐng)求,這個(gè)過(guò)程會(huì)對(duì)config,也就是我們發(fā)送請(qǐng)求時(shí)傳送的參數(shù)進(jìn)行一些操作。

而當(dāng)接收響應(yīng)的時(shí)候,會(huì)先執(zhí)行響應(yīng)攔截器的代碼,然后再把響應(yīng)的數(shù)據(jù)返回來(lái),這個(gè)過(guò)程會(huì)對(duì)response,也就是響應(yīng)的數(shù)據(jù)進(jìn)行一系列操作。

怎么實(shí)現(xiàn)呢?需要明確的是攔截器也是一個(gè)類,管理響應(yīng)和請(qǐng)求。因此我們先實(shí)現(xiàn)攔截器

  1. class InterceptorsManage { 
  2.   constructor() { 
  3.     this.handlers = []; 
  4.   } 
  5.  
  6.   use(fullfield, rejected) { 
  7.     this.handlers.push({ 
  8.       fullfield, 
  9.       rejected 
  10.     }) 
  11.   } 

我們是用這個(gè)語(yǔ)句axios.interceptors.response.use和axios.interceptors.request.use,來(lái)觸發(fā)攔截器執(zhí)行use方法的。

說(shuō)明axios上有一個(gè)響應(yīng)攔截器和一個(gè)請(qǐng)求攔截器。那怎么實(shí)現(xiàn)Axios呢?看代碼

  1. class Axios { 
  2.     constructor() { 
  3.         新增代碼 
  4.         this.interceptors = { 
  5.             request: new InterceptorsManage, 
  6.             response: new InterceptorsManage 
  7.         } 
  8.     } 
  9.  
  10.     request(config) { 
  11.         return new Promise(resolve => { 
  12.             const {url = '', method = 'get', data = {}} = config; 
  13.             // 發(fā)送ajax請(qǐng)求 
  14.             console.log(config); 
  15.             const xhr = new XMLHttpRequest(); 
  16.             xhr.open(method, url, true); 
  17.             xhr.onload = function() { 
  18.                 console.log(xhr.responseText) 
  19.                 resolve(xhr.responseText); 
  20.             }; 
  21.             xhr.send(data); 
  22.         }) 
  23.     } 

可見,axios實(shí)例上有一個(gè)對(duì)象interceptors。這個(gè)對(duì)象有兩個(gè)攔截器,一個(gè)用來(lái)處理請(qǐng)求,一個(gè)用來(lái)處理響應(yīng)。

所以,我們執(zhí)行語(yǔ)句axios.interceptors.response.use和axios.interceptors.request.use的時(shí)候,實(shí)現(xiàn)獲取axios實(shí)例上的interceptors對(duì)象,然后再獲取response或request攔截器,再執(zhí)行對(duì)應(yīng)的攔截器的use方法。

而執(zhí)行use方法,會(huì)把我們傳入的回調(diào)函數(shù)push到攔截器的handlers數(shù)組里。

到這里你有沒(méi)有發(fā)現(xiàn)一個(gè)問(wèn)題。這個(gè)interceptors對(duì)象是Axios上的啊,我們導(dǎo)出的是request方法啊(欸?好熟悉的問(wèn)題,上面提到過(guò)哈哈哈~~~額)。處理方法跟上面處理的方式一樣,都是把Axios上的方法和屬性搬到request過(guò)去,也就是遍歷Axios實(shí)例上的方法,得以將interceptors對(duì)象掛載到request上。

所以只要更改下CreateAxiosFn方法即可。

  1. function CreateAxiosFn() { 
  2.   let axios = new Axios(); 
  3.    
  4.   let req = axios.request.bind(axios); 
  5.   // 混入方法, 處理axios的request方法,使之擁有g(shù)et,post...方法 
  6.   utils.extend(req, Axios.prototype, axios) 
  7.   新增代碼 
  8.   utils.extend(req, axios) 
  9.   return req; 

好了,現(xiàn)在request也有了interceptors對(duì)象,那么什么時(shí)候拿interceptors對(duì)象中的handler之前保存的回調(diào)函數(shù)出來(lái)執(zhí)行。

沒(méi)錯(cuò),就是我們發(fā)送請(qǐng)求的時(shí)候,會(huì)先獲取request攔截器的handlers的方法來(lái)執(zhí)行。再執(zhí)行我們發(fā)送的請(qǐng)求,然后獲取response攔截器的handlers的方法來(lái)執(zhí)行。

因此,我們要修改之前所寫的request方法 之前是這樣的。

  1. request(config) { 
  2.     return new Promise(resolve => { 
  3.         const {url = '', method = 'get', data = {}} = config; 
  4.         // 發(fā)送ajax請(qǐng)求 
  5.         console.log(config); 
  6.         const xhr = new XMLHttpRequest(); 
  7.         xhr.open(method, url, true); 
  8.         xhr.onload = function() { 
  9.             console.log(xhr.responseText) 
  10.             resolve(xhr.responseText); 
  11.         }; 
  12.         xhr.send(data); 
  13.     }) 

但是現(xiàn)在request里不僅要執(zhí)行發(fā)送ajax請(qǐng)求,還要執(zhí)行攔截器handlers中的回調(diào)函數(shù)。所以,最好下就是將執(zhí)行ajax的請(qǐng)求封裝成一個(gè)方法

  1. request(config) { 
  2.     this.sendAjax(config) 
  3. sendAjax(config){ 
  4.     return new Promise(resolve => { 
  5.         const {url = '', method = 'get', data = {}} = config; 
  6.         // 發(fā)送ajax請(qǐng)求 
  7.         console.log(config); 
  8.         const xhr = new XMLHttpRequest(); 
  9.         xhr.open(method, url, true); 
  10.         xhr.onload = function() { 
  11.             console.log(xhr.responseText) 
  12.             resolve(xhr.responseText); 
  13.         }; 
  14.         xhr.send(data); 
  15.     }) 

好了,現(xiàn)在我們要獲得handlers中的回調(diào)

  1. request(config) { 
  2.     // 攔截器和請(qǐng)求組裝隊(duì)列 
  3.     let chain = [this.sendAjax.bind(this), undefined] // 成對(duì)出現(xiàn)的,失敗回調(diào)暫時(shí)不處理 
  4.  
  5.     // 請(qǐng)求攔截 
  6.     this.interceptors.request.handlers.forEach(interceptor => { 
  7.         chain.unshift(interceptor.fullfield, interceptor.rejected) 
  8.     }) 
  9.  
  10.     // 響應(yīng)攔截 
  11.     this.interceptors.response.handlers.forEach(interceptor => { 
  12.         chain.push(interceptor.fullfield, interceptor.rejected) 
  13.     }) 
  14.  
  15.     // 執(zhí)行隊(duì)列,每次執(zhí)行一對(duì),并給promise賦最新的值 
  16.     let promise = Promise.resolve(config); 
  17.     while(chain.length > 0) { 
  18.         promise = promise.then(chain.shift(), chain.shift()) 
  19.     } 
  20.     return promise; 

我們先把sendAjax請(qǐng)求和undefined放進(jìn)了chain數(shù)組里,再把請(qǐng)求攔截器的handlers的成對(duì)回調(diào)放到chain數(shù)組頭部。再把響應(yīng)攔截器的handlers的承兌回調(diào)反倒chain數(shù)組的尾部。

然后再 逐漸取數(shù) chain數(shù)組的成對(duì)回調(diào)執(zhí)行。

  1. promise = promise.then(chain.shift(), chain.shift()) 

這一句,實(shí)際上就是不斷將config從上一個(gè)promise傳遞到下一個(gè)promise,期間可能回調(diào)config做出一些修改。什么意思?我們結(jié)合一個(gè)例子來(lái)講解一下

首先攔截器是這樣使用的

  1. // 添加請(qǐng)求攔截器 
  2.  
  3. axios.interceptors.request.use(function (config) { 
  4.     // 在發(fā)送請(qǐng)求之前做些什么 
  5.     return config; 
  6.   }, function (error) { 
  7.     // 對(duì)請(qǐng)求錯(cuò)誤做些什么 
  8.     return Promise.reject(error); 
  9.   }); 
  10.  
  11. // 添加響應(yīng)攔截器 
  12. axios.interceptors.response.use(function (response) { 
  13.     // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么 
  14.     return response; 
  15.   }, function (error) { 
  16.     // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么 
  17.     return Promise.reject(error); 
  18.   }); 

然后執(zhí)行request的時(shí)候。chain數(shù)組的數(shù)據(jù)是這樣的

  1. chain = [ 
  2.   function (config) { 
  3.     // 在發(fā)送請(qǐng)求之前做些什么 
  4.     return config; 
  5.   },  
  6.    
  7.   function (error) { 
  8.     // 對(duì)請(qǐng)求錯(cuò)誤做些什么 
  9.     return Promise.reject(error); 
  10.   } 
  11.   this.sendAjax.bind(this),  
  12.    
  13.   undefined, 
  14.    
  15.   function (response) { 
  16.     // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么 
  17.     return response; 
  18.   },  
  19.   function (error) { 
  20.     // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么 
  21.     return Promise.reject(error); 
  22.   } 

首先
執(zhí)行第一次promise.then(chain.shift(), chain.shift()),即

  1. promise.then
  2.   function (config) { 
  3.     // 在發(fā)送請(qǐng)求之前做些什么 
  4.     return config; 
  5.   },  
  6.    
  7.   function (error) { 
  8.     // 對(duì)請(qǐng)求錯(cuò)誤做些什么 
  9.     return Promise.reject(error); 
  10.   } 

一般情況,promise是resolved狀態(tài),是執(zhí)行成功回調(diào)的,也就是執(zhí)行

  1. function (config) { 
  2.     // 在發(fā)送請(qǐng)求之前做些什么 
  3.     return config; 
  4.   },  

promise.then是要返回一個(gè)新的promise對(duì)象的。為了區(qū)分,在這里,我會(huì)把這個(gè)新的promise對(duì)象叫做第一個(gè)新的promise對(duì)象 這個(gè)第一個(gè)新的promise對(duì)象會(huì)把

  1. function (config) { 
  2.     // 在發(fā)送請(qǐng)求之前做些什么 
  3.     return config; 
  4.   },  

的執(zhí)行結(jié)果傳入resolve函數(shù)中

  1. resolve(config) 

使得這個(gè)返回的第一個(gè)新的promise對(duì)象的狀態(tài)為resovled,而且第一個(gè)新的promise對(duì)象的data為config。

這里需要對(duì)Promise的原理足夠理解。所以我前一篇文章寫的是手寫Promise核心原理,再也不怕面試官問(wèn)我Promise原理,你可以去看看

接下來(lái),再執(zhí)行

  1. promise.then
  2.   sendAjax(config) 
  3.   , 
  4.   undefined 

注意:這里的promise是 上面提到的第一個(gè)新的promise對(duì)象。

而promise.then這個(gè)的執(zhí)行又會(huì)返回第二個(gè)新的promise對(duì)象。

因?yàn)檫@里promise.then中的promise也就是第一個(gè)新的promise對(duì)象的狀態(tài)是resolved的,所以會(huì)執(zhí)行sendAjax()。而且會(huì)取出第一個(gè)新的promise對(duì)象的data 作為config轉(zhuǎn)入sendAjax()。

當(dāng)sendAjax執(zhí)行完,就會(huì)返回一個(gè)response。這個(gè)response就會(huì)保存在第二個(gè)新的promise對(duì)象的data中。

接下來(lái),再執(zhí)行

  1. promise.then
  2.   function (response) { 
  3.     // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么 
  4.     return response; 
  5.   },  
  6.   function (error) { 
  7.     // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么 
  8.     return Promise.reject(error); 
  9.   } 

同樣,會(huì)把第二個(gè)新的promise對(duì)象的data取出來(lái)作為response參數(shù)傳入

  1. function (response) { 
  2.     // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么 
  3.     return response; 
  4.   },  

飯后返回一個(gè)promise對(duì)象,這個(gè)promise對(duì)象的data保存了這個(gè)函數(shù)的執(zhí)行結(jié)果,也就是返回值response。

然后通過(guò)return promise;

把這個(gè)promise返回了。咦?是怎么取出promise的data的。我們看看我們平常事怎么獲得響應(yīng)數(shù)據(jù)的

  1. axios.get('http://localhost:5000/getTest'
  2.     .then(res => { 
  3.          console.log('getAxios 成功響應(yīng)', res); 
  4.     }) 

在then里接收響應(yīng)數(shù)據(jù)。所以原理跟上面一樣,將返回的promise的data作為res參數(shù)了。

現(xiàn)在看看我們的myAxios完整代碼吧,好有個(gè)全面的了解

  1. class InterceptorsManage { 
  2.     constructor() { 
  3.         this.handlers = []; 
  4.     } 
  5.  
  6.     use(fullfield, rejected) { 
  7.         this.handlers.push({ 
  8.             fullfield, 
  9.             rejected 
  10.         }) 
  11.     } 
  12.  
  13. class Axios { 
  14.     constructor() { 
  15.         this.interceptors = { 
  16.             request: new InterceptorsManage, 
  17.             response: new InterceptorsManage 
  18.         } 
  19.     } 
  20.  
  21.     request(config) { 
  22.         // 攔截器和請(qǐng)求組裝隊(duì)列 
  23.         let chain = [this.sendAjax.bind(this), undefined] // 成對(duì)出現(xiàn)的,失敗回調(diào)暫時(shí)不處理 
  24.  
  25.         // 請(qǐng)求攔截 
  26.         this.interceptors.request.handlers.forEach(interceptor => { 
  27.             chain.unshift(interceptor.fullfield, interceptor.rejected) 
  28.         }) 
  29.  
  30.         // 響應(yīng)攔截 
  31.         this.interceptors.response.handlers.forEach(interceptor => { 
  32.             chain.push(interceptor.fullfield, interceptor.rejected) 
  33.         }) 
  34.  
  35.         // 執(zhí)行隊(duì)列,每次執(zhí)行一對(duì),并給promise賦最新的值 
  36.         let promise = Promise.resolve(config); 
  37.         while(chain.length > 0) { 
  38.             promise = promise.then(chain.shift(), chain.shift()) 
  39.         } 
  40.         return promise; 
  41.     } 
  42.     sendAjax(){ 
  43.         return new Promise(resolve => { 
  44.             const {url = '', method = 'get', data = {}} = config; 
  45.             // 發(fā)送ajax請(qǐng)求 
  46.             console.log(config); 
  47.             const xhr = new XMLHttpRequest(); 
  48.             xhr.open(method, url, true); 
  49.             xhr.onload = function() { 
  50.                 console.log(xhr.responseText) 
  51.                 resolve(xhr.responseText); 
  52.             }; 
  53.             xhr.send(data); 
  54.         }) 
  55.     } 
  56.  
  57. // 定義get,post...方法,掛在到Axios原型上 
  58. const methodsArr = ['get''delete''head''options''put''patch''post']; 
  59. methodsArr.forEach(met => { 
  60.     Axios.prototype[met] = function() { 
  61.         console.log('執(zhí)行'+met+'方法'); 
  62.         // 處理單個(gè)方法 
  63.         if (['get''delete''head''options'].includes(met)) { // 2個(gè)參數(shù)(url[, config]) 
  64.             return this.request({ 
  65.                 method: met, 
  66.                 url: arguments[0], 
  67.                 ...arguments[1] || {} 
  68.             }) 
  69.         } else { // 3個(gè)參數(shù)(url[,data[,config]]) 
  70.             return this.request({ 
  71.                 method: met, 
  72.                 url: arguments[0], 
  73.                 data: arguments[1] || {}, 
  74.                 ...arguments[2] || {} 
  75.             }) 
  76.         } 
  77.  
  78.     } 
  79. }) 
  80.  
  81.  
  82. // 工具方法,實(shí)現(xiàn)b的方法混入a; 
  83. // 方法也要混入進(jìn)去 
  84. const utils = { 
  85.     extend(a,b, context) { 
  86.         for(let key in b) { 
  87.             if (b.hasOwnProperty(key)) { 
  88.                 if (typeof b[key] === 'function') { 
  89.                     a[key] = b[key].bind(context); 
  90.                 } else { 
  91.                     a[key] = b[key
  92.                 } 
  93.             } 
  94.  
  95.         } 
  96.     } 
  97.  
  98.  
  99. // 最終導(dǎo)出axios的方法-》即實(shí)例的request方法 
  100. function CreateAxiosFn() { 
  101.     let axios = new Axios(); 
  102.  
  103.     let req = axios.request.bind(axios); 
  104.     // 混入方法, 處理axios的request方法,使之擁有g(shù)et,post...方法 
  105.     utils.extend(req, Axios.prototype, axios) 
  106.     return req; 
  107.  
  108. // 得到最后的全局變量axios 
  109. let axios = CreateAxiosFn(); 

來(lái)測(cè)試下攔截器功能是否正常

  1. <script type="text/javascript" src="./myAxios.js"></script> 
  2.  
  3. <body> 
  4. <button class="btn">點(diǎn)我發(fā)送請(qǐng)求</button> 
  5. <script> 
  6.     // 添加請(qǐng)求攔截器 
  7.     axios.interceptors.request.use(function (config) { 
  8.         // 在發(fā)送請(qǐng)求之前做些什么 
  9.         config.method = "get"
  10.         console.log("被我請(qǐng)求攔截器攔截了,哈哈:",config); 
  11.         return config; 
  12.     }, function (error) { 
  13.         // 對(duì)請(qǐng)求錯(cuò)誤做些什么 
  14.         return Promise.reject(error); 
  15.     }); 
  16.  
  17.     // 添加響應(yīng)攔截器 
  18.     axios.interceptors.response.use(function (response) { 
  19.         // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么 
  20.         console.log("被我響應(yīng)攔截?cái)r截了,哈哈 "); 
  21.         response = {message:"響應(yīng)數(shù)據(jù)被我替換了,啊哈哈哈"
  22.         return response; 
  23.     }, function (error) { 
  24.         // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么 
  25.         console.log("錯(cuò)了嗎"); 
  26.         return Promise.reject(error); 
  27.     }); 
  28.     document.querySelector('.btn').onclick = function() { 
  29.         // 分別使用以下方法調(diào)用,查看myaxios的效果 
  30.         axios({ 
  31.           url: 'http://localhost:5000/getTest' 
  32.         }).then(res => { 
  33.           console.log('response', res); 
  34.         }) 
  35.     } 
  36. </script> 
  37. </body> 

攔截成功?。。。?!

 

責(zé)任編輯:姜華 來(lái)源: 前端陽(yáng)光
相關(guān)推薦

2020-11-24 07:48:32

React

2021-08-10 18:36:02

Express原理面試

2022-08-27 13:49:36

ES7promiseresolve

2020-10-23 09:26:57

React-Redux

2021-05-08 07:53:33

面試線程池系統(tǒng)

2022-04-01 07:52:42

JavaScript防抖節(jié)流

2020-12-03 08:14:45

Axios核心Promise

2022-10-31 11:10:49

Javavolatile變量

2021-11-24 10:10:32

axios前端攔截器

2023-11-28 17:49:51

watch?computed?性能

2020-10-15 12:52:46

SpringbootJava編程語(yǔ)言

2021-04-22 07:49:51

Vue3Vue2.xVue3.x

2020-12-09 10:29:53

SSH加密數(shù)據(jù)安全

2024-08-22 10:39:50

@Async注解代理

2024-03-05 10:33:39

AOPSpring編程

2025-03-07 00:00:10

2021-12-02 08:19:06

MVCC面試數(shù)據(jù)庫(kù)

2020-11-02 09:35:04

ReactHook

2024-11-19 15:13:02

2024-08-29 16:30:27

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)