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

Axios 是如何封裝 HTTP 請(qǐng)求的

開(kāi)發(fā) 前端
本文用來(lái)整理項(xiàng)目中常用的 Axios 的封裝使用。同時(shí)學(xué)習(xí)源碼,手寫實(shí)現(xiàn) Axios 的核心代碼。

Axios 毋庸多說(shuō)大家在前端開(kāi)發(fā)中常用的一個(gè)發(fā)送 HTTP 請(qǐng)求的庫(kù),用過(guò)的都知道。本文用來(lái)整理項(xiàng)目中常用的 Axios 的封裝使用。同時(shí)學(xué)習(xí)源碼,手寫實(shí)現(xiàn) Axios 的核心代碼。

Axios 常用封裝

是什么

Axios 是一個(gè)基于 promise 的 HTTP 庫(kù),可以用在瀏覽器和 node.js 中。它的特性:

  •  從瀏覽器中創(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官網(wǎng)地址:http://www.axios-js.com/zh-cn/docs/#axios-config

Axios 使用方式有兩種:一種是直接使用全局的 Axios 對(duì)象;另外一種是通過(guò) axios.create(config) 方法創(chuàng)建一個(gè)實(shí)例對(duì)象,使用該對(duì)象。兩種方式的區(qū)別是通過(guò)第二種方式創(chuàng)建的實(shí)例對(duì)象更清爽一些;全局的 Axios 對(duì)象其實(shí)也是創(chuàng)建的實(shí)例對(duì)象導(dǎo)出的,它本身上加載了很多默認(rèn)屬性。后面源碼學(xué)習(xí)的時(shí)候會(huì)再詳細(xì)說(shuō)明。

請(qǐng)求

Axios 這個(gè) HTTP 的庫(kù)比較靈活,給用戶多種發(fā)送請(qǐng)求的方式,以至于有些混亂。細(xì)心整理會(huì)發(fā)現(xiàn),全局的 Axios(或者 axios.create(config)創(chuàng)建的對(duì)象) 既可以當(dāng)作對(duì)象使用,也可以當(dāng)作函數(shù)使用: 

  1. // axios 當(dāng)作對(duì)象使用  
  2. axios.request(config)  
  3. axios.get(url[, config])  
  4. axios.post(url[, data[, config]])  
  1. // axios() 當(dāng)作函數(shù)使用。 發(fā)送 POST 請(qǐng)求  
  2. axios({  
  3.   method: 'post',  
  4.   url: '/user/12345',  
  5.   data: {  
  6.     firstName: 'Fred',  
  7.     lastName: 'Flintstone'  
  8.   }  
  9. }); 

后面源碼學(xué)習(xí)的時(shí)候會(huì)再詳細(xì)說(shuō)明為什么 Axios 可以實(shí)現(xiàn)兩種方式的使用。

取消請(qǐng)求

可以使用 CancelToken.source 工廠方法創(chuàng)建 cancel token: 

  1. const CancelToken = axios.CancelToken;  
  2. const source = CancelToken.source();  
  3. axios.get('/user/12345', {  
  4.   cancelToken: source.token  
  5. }).catch(function(thrown) {  
  6.   if (axios.isCancel(thrown)) {  
  7.     console.log('Request canceled', thrown.message);  
  8.   } else { 
  9.       // 處理錯(cuò)誤  
  10.   }  
  11. });  
  12. // 取消請(qǐng)求(message 參數(shù)是可選的)  
  13. source.cancel('Operation canceled by the user.'); 

source 有兩個(gè)屬性:一個(gè)是 source.token 標(biāo)識(shí)請(qǐng)求;另一個(gè)是 source.cancel() 方法,該方法調(diào)用后,可以讓 CancelToken 實(shí)例的 promise 狀態(tài)變?yōu)?resolved,從而觸發(fā) xhr 對(duì)象的 abort() 方法,取消請(qǐng)求。

攔截

Axios 還有一個(gè)奇妙的功能點(diǎn),可以在發(fā)送請(qǐng)求前對(duì)請(qǐng)求進(jìn)行攔截,對(duì)相應(yīng)結(jié)果進(jìn)行攔截。結(jié)合業(yè)務(wù)場(chǎng)景的話,在中臺(tái)系統(tǒng)中完成登錄后,獲取到后端返回的 token,可以將 token 添加到 header 中,以后所有的請(qǐng)求自然都會(huì)加上這個(gè)自定義 header。 

  1. //攔截1 請(qǐng)求攔截  
  2. instance.interceptors.request.use(function(config){  
  3.     //在發(fā)送請(qǐng)求之前做些什么  
  4.     const token = sessionStorage.getItem('token');  
  5.     if(token){  
  6.         const newConfig = {  
  7.             ...config,  
  8.             headers: {  
  9.                 token: token  
  10.             }  
  11.         }  
  12.         return newConfig;  
  13.     }else{  
  14.         return config;  
  15.     }  
  16. }, function(error){  
  17.     //對(duì)請(qǐng)求錯(cuò)誤做些什么  
  18.     return Promise.reject(error);  
  19. }); 

我們還可以利用請(qǐng)求攔截功能實(shí)現(xiàn) 取消重復(fù)請(qǐng)求,也就是在前一個(gè)請(qǐng)求還沒(méi)有返回之前,用戶重新發(fā)送了請(qǐng)求,需要先取消前一次請(qǐng)求,再發(fā)送新的請(qǐng)求。比如搜索框自動(dòng)查詢,當(dāng)用戶修改了內(nèi)容重新發(fā)送請(qǐng)求的時(shí)候需要取消前一次請(qǐng)求,避免請(qǐng)求和響應(yīng)混亂。再比如表單提交按鈕,用戶多次點(diǎn)擊提交按鈕,那么我們就需要取消掉之前的請(qǐng)求,保證只有一次請(qǐng)求的發(fā)送和響應(yīng)。

實(shí)現(xiàn)原理是使用一個(gè)對(duì)象記錄已經(jīng)發(fā)出去的請(qǐng)求,在請(qǐng)求攔截函數(shù)中先判斷這個(gè)對(duì)象中是否記錄了本次請(qǐng)求信息,如果已經(jīng)存在,則取消之前的請(qǐng)求,將本次請(qǐng)求添加進(jìn)去對(duì)象中;如果沒(méi)有記錄過(guò)本次請(qǐng)求,則將本次請(qǐng)求信息添加進(jìn)對(duì)象中。最后請(qǐng)求完成后,在響應(yīng)攔截函數(shù)中執(zhí)行刪除本次請(qǐng)求信息的邏輯。 

  1. // 攔截2   重復(fù)請(qǐng)求,取消前一個(gè)請(qǐng)求  
  2. const promiseArr = {};  
  3. instance.interceptors.request.use(function(config){  
  4.     console.log(Object.keys(promiseArr).length)  
  5.     //在發(fā)送請(qǐng)求之前做些什么  
  6.     let source=null 
  7.     if(config.cancelToken){  
  8.         // config 配置中帶了 source 信息  
  9.         source = config.source;  
  10.     }else{  
  11.         const CancelToken = axios.CancelToken;  
  12.         source = CancelToken.source();  
  13.         config.cancelToken = source.token;  
  14.     }  
  15.     const currentKey = getRequestSymbol(config);  
  16.     if(promiseArr[currentKey]){  
  17.         const tmp = promiseArr[currentKey];  
  18.         tmp.cancel("取消前一個(gè)請(qǐng)求");  
  19.         delete promiseArr[currentKey];  
  20.         promiseArr[currentKey] = source;  
  21.     }else{  
  22.         promiseArr[currentKey] = source;  
  23.     }  
  24.     return config;  
  25. }, function(error){  
  26.     //對(duì)請(qǐng)求錯(cuò)誤做些什么  
  27.     return Promise.reject(error);  
  28. });  
  29. // 根據(jù) url、method、params 生成唯一標(biāo)識(shí),大家可以自定義自己的生成規(guī)則  
  30. function getRequestSymbol(config){  
  31.     const arr = [];  
  32.     if(config.params){  
  33.         const data = config.params;  
  34.         for(let key of Object.keys(data)){  
  35.             arr.push(key+"&"+data[key]);  
  36.         }  
  37.         arr.sort();  
  38.     }  
  39.     return config.url+config.method+arr.join("");  
  40.  
  41. instance.interceptors.response.use(function(response){  
  42.     const currentKey = getRequestSymbol(response.config);  
  43.     delete promiseArr[currentKey];  
  44.     return response;  
  45. }, function(error){  
  46.     //對(duì)請(qǐng)求錯(cuò)誤做些什么  
  47.     return Promise.reject(error);  
  48. }); 

最后,我們可以在響應(yīng)攔截函數(shù)中統(tǒng)一處理返回碼的邏輯: 

  1. // 響應(yīng)攔截  
  2. instance.interceptors.response.use(function(response){  
  3.     // 401 沒(méi)有登錄跳轉(zhuǎn)到登錄頁(yè)面  
  4.     if(response.data.code===401){  
  5.         window.location.href = "http://127.0.0.1:8080/#/login" 
  6.     }else if(response.data.code===403){  
  7.         // 403 無(wú)權(quán)限跳轉(zhuǎn)到無(wú)權(quán)限頁(yè)面  
  8.         window.location.href = "http://127.0.0.1:8080/#/noAuth" 
  9.     }  
  10.     return response;  
  11. }, function(error){  
  12.     //對(duì)請(qǐng)求錯(cuò)誤做些什么  
  13.     return Promise.reject(error);  
  14. }) 

文件下載

通常文件下載有兩種方式:一種是通過(guò)文件在服務(wù)器上的對(duì)外地址直接下載;還有一種是通過(guò)接口將文件以二進(jìn)制流的形式下載。

第一種:同域名 下使用 a 標(biāo)簽下載: 

  1. // httpServer.js  
  2. const express = require("express");  
  3. const path = require('path');  
  4. const app = express();  
  5. //靜態(tài)文件地址  
  6. app.use(express.static(path.join(__dirname, 'public')))  
  7. app.use(express.static(path.join(__dirname, '../')));  
  8. app.listen(8081, () => {  
  9.   console.log("服務(wù)器啟動(dòng)成功!")  
  10. });  
  1. // index.html  
  2. <a href="test.txt" download="test.txt">下載</a> 

第二種:二進(jìn)制文件流的形式傳遞,我們直接訪問(wèn)該接口并不能下載文件,一定程度保證了數(shù)據(jù)的安全性。比較多的場(chǎng)景是:后端接收到查詢參數(shù),查詢數(shù)據(jù)庫(kù)然后通過(guò)插件動(dòng)態(tài)生成 excel 文件,以文件流的方式讓前端下載。

這時(shí)候,我們可以將請(qǐng)求文件下載的邏輯進(jìn)行封裝。將二進(jìn)制文件流存在 Blob 對(duì)象中,再將其轉(zhuǎn)為 url 對(duì)象,最后通過(guò) a 標(biāo)簽下載。 

  1. //封裝下載  
  2. export function downLoadFetch(url, params = {}, config={}) {  
  3.     //取消  
  4.     const downSource = axios.CancelToken.source();  
  5.     document.getElementById('downAnimate').style.display = 'block' 
  6.     document.getElementById('cancelBtn').addEventListener('click', function(){  
  7.         downSource.cancel("用戶取消下載");  
  8.         document.getElementById('downAnimate').style.display = 'none' 
  9.     }, false);  
  10.     //參數(shù)  
  11.     config.params = params;  
  12.     //超時(shí)時(shí)間  
  13.     configconfig.timeout = config.timeout ? config.timeout : defaultDownConfig.timeout;  
  14.     //類型  
  15.     config.responseType = defaultDownConfig.responseType;  
  16.     //取消下載  
  17.     config.cancelToken = downSource.token;  
  18.     return instance.get(url, config).then(response=> 
  19.         const content = response.data;  
  20.         const url = window.URL.createObjectURL(new Blob([content]));  
  21.         //創(chuàng)建 a 標(biāo)簽  
  22.         const link = document.createElement('a');  
  23.         link.style.display = 'none' 
  24.         link.href = url 
  25.         //文件名  Content-Disposition: attachment; filename=download.txt  
  26.         const filename = response.headers['content-disposition'].split(";")[1].split("=")[1];  
  27.         link.download = filename 
  28.         document.body.appendChild(link);  
  29.         link.click();  
  30.         document.body.removeChild(link);  
  31.         return {  
  32.             status: 200,  
  33.             success: true  
  34.         }  
  35.     })  

手寫 Axios 核心代碼

寫了這么多用法終于到正題了,手寫 Axios 核心代碼。Axios 這個(gè)庫(kù)源碼不難閱讀,沒(méi)有特別復(fù)雜的邏輯,大家可以放心閱讀 😂 。

源碼入口是這樣查找:在項(xiàng)目 node_modules 目錄下,找到 axios 模塊的 package.json 文件,其中 "main": "index.js", 就是文件入口。一步步我們可以看到源碼是怎么串起來(lái)的。

模仿上面的目錄結(jié)構(gòu),我們創(chuàng)建自己的目錄結(jié)構(gòu): 

  1. axios-js  
  2. │  index.html  
  3. │    
  4. └─lib  
  5.         adapter.js  
  6.         Axios.js  
  7.         axiosInstance.js  
  8.         CancelToken.js  
  9.         InterceptorManager.js 

Axios 是什么

上面有提到我們使用的全局 Axios 對(duì)象其實(shí)也是構(gòu)造出來(lái)的 axios,既可以當(dāng)對(duì)象使用調(diào)用 get、post 等方法,也可以直接當(dāng)作函數(shù)使用。這是因?yàn)槿值?Axios 其實(shí)是函數(shù)對(duì)象 instance 。源碼位置在 axios/lib/axios.js 中。具體代碼如下: 

  1. // axios/lib/axios.js  
  2. //創(chuàng)建 axios 實(shí)例  
  3. function createInstance(defaultConfig) {  
  4.   var context = new Axios(defaultConfig);  
  5.   //instance 對(duì)象是 bind 返回的函數(shù)  
  6.   var instance = bind(Axios.prototype.request, context);  
  7.   // Copy axios.prototype to instance  
  8.   utils.extend(instance, Axios.prototype, context);  
  9.   // Copy context to instance  
  10.   utils.extend(instance, context);  
  11.   return instance;  
  12.  
  13. // 實(shí)例一個(gè) axios  
  14. var axios = createInstance(defaults);  
  15. // 向這個(gè)實(shí)例添加 Axios 屬性  
  16. axios.Axios = Axios;  
  17. // 向這個(gè)實(shí)例添加 create 方法  
  18. axios.create = function create(instanceConfig) {  
  19.   return createInstance(mergeConfig(axios.defaults, instanceConfig));  
  20. };  
  21. // 向這個(gè)實(shí)例添加 CancelToken 方法  
  22. axios.CancelToken = require('./cancel/CancelToken'); 
  23. // 導(dǎo)出實(shí)例 axios  
  24. module.exports.default = axios

根據(jù)上面的源碼,我們可以簡(jiǎn)寫一下自己實(shí)現(xiàn) Axios.js 和 axiosInstance.js: 

  1. // Axios.js  
  2. //Axios 主體  
  3. function Axios(config){ 
  4.  
  5. // 核心方法,發(fā)送請(qǐng)求  
  6. Axios.prototype.request = function(config){  
  7.  
  8. Axios.prototype.get = function(url, config={}){  
  9.     return this.request({url: url, method: 'GET', ...config});  
  10.  
  11. Axios.prototype.post = function(url, data, config={}){  
  12.     return this.request({url: url, method: 'POST', data: data, ...config})  
  13.  
  14. export default Axios; 

在 axiosInstance.js 文件中,實(shí)例化一個(gè) Axios 得到 context,再將原型對(duì)象上的方法綁定到 instance 對(duì)象上,同時(shí)將 context 的屬性添加到 instance 上。這樣 instance 就成為了一個(gè)函數(shù)對(duì)象。既可以當(dāng)作對(duì)象使用,也可以當(dāng)作函數(shù)使用。 

  1. // axiosInstance.js  
  2. //創(chuàng)建實(shí)例  
  3. function createInstance(config){  
  4.     const context = new Axios(config);  
  5.     var instance = Axios.prototype.request.bind(context);  
  6.     //將 Axios.prototype 屬性擴(kuò)展到 instance 上  
  7.     for(let k of Object.keys(Axios.prototype)){  
  8.         instance[k] = Axios.prototype[k].bind(context);  
  9.     }  
  10.     //將 context 屬性擴(kuò)展到 instance 上  
  11.     for(let k of Object.keys(context)){  
  12.         instance[k] = context[k]  
  13.     }  
  14.     return instance;  
  15.  
  16. const axios = createInstance({});  
  17. axios.create = function(config){  
  18.     return createInstance(config);  
  19.  export default axios; 

也就是說(shuō) axios.js 中導(dǎo)出的 axios 對(duì)象并不是 new Axios() 方法返回的對(duì)象 context,而是 Axios.prototype.request.bind(context) 執(zhí)行返回的 instance,通過(guò)遍歷 Axios.prototype 并改變其 this 指向到 context;遍歷 context 對(duì)象讓 instance 對(duì)象具有 context 的所有屬性。這樣 instance 對(duì)象就無(wú)敵了,😎 既擁有了 Axios.prototype 上的所有方法,又具有了 context 的所有屬性。

請(qǐng)求實(shí)現(xiàn)

我們知道 Axios 在瀏覽器中會(huì)創(chuàng)建 XMLHttpRequest 對(duì)象,在 node.js 環(huán)境中創(chuàng)建 http 發(fā)送請(qǐng)求。Axios.prototype.request() 是發(fā)送請(qǐng)求的核心方法,這個(gè)方法其實(shí)調(diào)用的是 dispatchRequest 方法,而 dispatchRequest 方法調(diào)用的是 config.adapter || defaults.adapter 也就是自定義的 adapter 或者默認(rèn)的 defaults.adapter,默認(rèn)defaults.adapter 調(diào)用的是 getDefaultAdapter 方法,源碼: 

  1. function getDefaultAdapter() {  
  2.   var adapter;  
  3.   if (typeof XMLHttpRequest !== 'undefined') {  
  4.     // For browsers use XHR adapter  
  5.     adapter = require('./adapters/xhr');  
  6.   } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {  
  7.     // For node use HTTP adapter  
  8.     adapter = require('./adapters/http');  
  9.   }  
  10.   return adapter;  

哈哈哈,getDefaultAdapter 方法最終根據(jù)當(dāng)前的環(huán)境返回不同的實(shí)現(xiàn)方法,這里用到了 適配器模式。我們只用實(shí)現(xiàn) xhr 發(fā)送請(qǐng)求即可: 

  1. //適配器 adapter.js  
  2. function getDefaultAdapter(){  
  3.     var adapter;  
  4.     if(typeof XMLHttpRequest !== 'undefined'){  
  5.         //導(dǎo)入 XHR 對(duì)象請(qǐng)求  
  6.         adapter = (config)=> 
  7.             return xhrAdapter(config);  
  8.         }  
  9.     }  
  10.     return adapter;  
  11.  
  12. function xhrAdapter(config){  
  13.     return new Promise((resolve, reject)=> 
  14.         var xhr = new XMLHttpRequest();  
  15.         xhr.open(config.method, config.url, true);  
  16.         xhr.send();  
  17.         xhr.onreadystatechange = ()=> 
  18.             if(xhr.readyState===4){  
  19.                 if(xhr.status>=200&&xhr.status<300){  
  20.                     resolve({  
  21.                         data: {},  
  22.                         status: xhr.status,  
  23.                         statusText: xhr.statusText,  
  24.                         xhr: xhr 
  25.                     })  
  26.                 }else{  
  27.                     reject({ 
  28.                          status: xhr.status  
  29.                     })  
  30.                 }  
  31.             }  
  32.         };  
  33.     })  
  34.  export default getDefaultAdapter; 

這樣就理順了,getDefaultAdapter 方法每次執(zhí)行會(huì)返回一個(gè) Promise 對(duì)象,這樣 Axios.prototype.request 方法可以得到執(zhí)行 xhr 發(fā)送請(qǐng)求的 Promise 對(duì)象。

給我們的 Axios.js 添加發(fā)送請(qǐng)求的方法: 

  1. //Axios.js  
  2. import getDefaultAdapter from './adapter.js';  
  3. Axios.prototype.request = function(config){  
  4.     const adapter = getDefaultAdapter(config);  
  5.     var promise = Promise.resolve(config);  
  6.     var chain = [adapter, undefined];  
  7.     while(chain.length){  
  8.         promisepromise = promise.then(chain.shift(), chain.shift());  
  9.     }  
  10.     return promise;  

攔截器實(shí)現(xiàn)

攔截器的原理在于 Axios.prototype.request 方法中的 chain 數(shù)組,把請(qǐng)求攔截函數(shù)添加到 chain 數(shù)組前面,把響應(yīng)攔截函數(shù)添加到數(shù)組后面。這樣就可以實(shí)現(xiàn)發(fā)送前攔截和響應(yīng)后攔截的效果。

創(chuàng)建 InterceptorManager.js 

  1. //InterceptorManager.js   
  2. //攔截器  
  3. function InterceptorManager(){  
  4.     this.handlers = [];  
  5.  
  6. InterceptorManager.prototype.use = function(fulfilled, rejected){  
  7.     this.handlers.push({  
  8.         fulfilled: fulfilled,  
  9.         rejected: rejected  
  10.     });  
  11.     return this.handlers.length -1;  
  12.  
  13. export default InterceptorManager; 

在 Axios.js 文件中,構(gòu)造函數(shù)有 interceptors屬性: 

  1. //Axios.js  
  2. function Axios(config){  
  3.     this.interceptors = {  
  4.         request: new InterceptorManager(),  
  5.         response: new InterceptorManager()  
  6.     }  

這樣我們?cè)?Axios.prototype.request 方法中對(duì)攔截器添加處理: 

  1. //Axios.js  
  2. Axios.prototype.request = function(config){  
  3.     const adapter = getDefaultAdapter(config);  
  4.     var promise = Promise.resolve(config);  
  5.     var chain = [adapter, undefined];  
  6.     //請(qǐng)求攔截  
  7.     this.interceptors.request.handlers.forEach(item=> 
  8.         chain.unshift(item.rejected);  
  9.         chain.unshift(item.fulfilled);      
  10.      });  
  11.     //響應(yīng)攔截  
  12.     this.interceptors.response.handlers.forEach(item=> 
  13.         chain.push(item.fulfilled);  
  14.         chain.push(item.rejected)  
  15.     });  
  16.     console.dir(chain);  
  17.     while(chain.length){  
  18.         promisepromise = promise.then(chain.shift(), chain.shift());  
  19.     }  
  20.     return promise;  

所以攔截器的執(zhí)行順序是:請(qǐng)求攔截2 -> 請(qǐng)求攔截1 -> 發(fā)送請(qǐng)求 -> 響應(yīng)攔截1 -> 響應(yīng)攔截2

取消請(qǐng)求

來(lái)到 Axios 最精彩的部分了,取消請(qǐng)求。我們知道 xhr 的 xhr.abort(); 函數(shù)可以取消請(qǐng)求。那么什么時(shí)候執(zhí)行這個(gè)取消請(qǐng)求的操作呢?得有一個(gè)信號(hào)告訴 xhr 對(duì)象什么時(shí)候執(zhí)行取消操作。取消請(qǐng)求就是未來(lái)某個(gè)時(shí)候要做的事情,你能想到什么呢?對(duì),就是 Promise。Promise 的 then 方法只有 Promise 對(duì)象的狀態(tài)變?yōu)?resolved 的時(shí)候才會(huì)執(zhí)行。我們可以利用這個(gè)特點(diǎn),在 Promise 對(duì)象的 then 方法中執(zhí)行取消請(qǐng)求的操作??创a: 

  1. //CancelToken.js  
  2. // 取消請(qǐng)求  
  3. function CancelToken(executor){  
  4.     if(typeof executor !== 'function'){  
  5.         throw new TypeError('executor must be a function.')  
  6.     }  
  7.     var resolvePromise;  
  8.     this.promise = new Promise((resolve)=> 
  9.         resolveresolvePromise = resolve;  
  10.     });  
  11.     executor(resolvePromise)  
  12.  
  13. CancelToken.source = function(){  
  14.     var cancel;  
  15.     var token = new CancelToken((c)=> 
  16.         ccancel = c;  
  17.     })  
  18.     return { 
  19.          token,  
  20.         cancel  
  21.     };  
  22.  
  23. export default CancelToken; 

當(dāng)我們執(zhí)行 const source = CancelToken.source()的時(shí)候,source 對(duì)象有兩個(gè)字段,一個(gè)是 token 對(duì)象,另一個(gè)是 cancel 函數(shù)。在 xhr 請(qǐng)求中: 

  1. //適配器  
  2. // adapter.js  
  3. function xhrAdapter(config){  
  4.     return new Promise((resolve, reject)=> 
  5.         ...  
  6.         //取消請(qǐng)求  
  7.         if(config.cancelToken){  
  8.             // 只有 resolved 的時(shí)候才會(huì)執(zhí)行取消操作  
  9.             config.cancelToken.promise.then(function onCanceled(cancel){  
  10.                 if(!xhr){  
  11.                     return;  
  12.                 }  
  13.                 xhr.abort();  
  14.                 reject("請(qǐng)求已取消"); 
  15.                  // clean up xhr  
  16.                 xhr = null 
  17.             })  
  18.         }  
  19.     })  

CancelToken 的構(gòu)造函數(shù)中需要傳入一個(gè)函數(shù),而這個(gè)函數(shù)的作用其實(shí)是為了將能控制內(nèi)部 Promise 的 resolve 函數(shù)暴露出去,暴露給 source 的 cancel 函數(shù)。這樣內(nèi)部的 Promise 狀態(tài)就可以通過(guò) source.cancel() 方法來(lái)控制啦,秒啊~ 👍

node 后端接口

node 后端簡(jiǎn)單的接口代碼: 

  1. const express = require("express");  
  2. const bodyParser = require('body-parser');  
  3. const app = express();  
  4. const router = express.Router();  
  5. //文件下載  
  6. const fs = require("fs");  
  7. // get 請(qǐng)求  
  8. router.get("/getCount", (req, res)=> 
  9.   setTimeout(()=> 
  10.     res.json({  
  11.       success: true,  
  12.       code: 200,  
  13.       data: 100  
  14.     })  
  15.   }, 1000)  
  16. })  
  17. // 二進(jìn)制文件流 
  18. router.get('/downFile', (req, res, next) => {  
  19.   var name = 'download.txt' 
  20.   var path = './' + name;  
  21.   var size = fs.statSync(path).size;  
  22.   var f = fs.createReadStream(path);  
  23.   res.writeHead(200, {  
  24.     'Content-Type': 'application/force-download',  
  25.     'Content-Disposition': 'attachment; filename=' + name,  
  26.     'Content-Length': size  
  27.   });  
  28.   f.pipe(res);  
  29. })  
  30. // 設(shè)置跨域訪問(wèn)  
  31. app.all("*", function (request, response, next) { 
  32.   // 設(shè)置跨域的域名,* 代表允許任意域名跨域;http://localhost:8080 表示前端請(qǐng)求的 Origin 地址  
  33.   response.header("Access-Control-Allow-Origin", "http://127.0.0.1:5500");  
  34.   //設(shè)置請(qǐng)求頭 header 可以加那些屬性  
  35.   response.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');  
  36.   //暴露給 axios https://blog.csdn.net/w345731923/article/details/114067074  
  37.   response.header("Access-Control-Expose-Headers", "Content-Disposition");  
  38.   // 設(shè)置跨域可以攜帶 Cookie 信息  
  39.   response.header('Access-Control-Allow-Credentials', "true");  
  40.   //設(shè)置請(qǐng)求頭哪些方法是合法的  
  41.   response.header(  
  42.     "Access-Control-Allow-Methods",  
  43.     "PUT,POST,GET,DELETE,OPTIONS"  
  44.   );  
  45.   response.header("Content-Type", "application/json;charset=utf-8");  
  46.   next();  
  47. });  
  48. // 接口數(shù)據(jù)解析  
  49. app.use(bodyParser.json())  
  50. app.use(bodyParser.urlencoded({  
  51.   extended: false  
  52. }))  
  53. app.use('/api', router) // 路由注冊(cè)  
  54. app.listen(8081, () => {  
  55.   console.log("服務(wù)器啟動(dòng)成功!")  
  56. }); 

git 地址

如果大家能夠跟著源碼敲一遍,相信一定會(huì)有很多收獲。 

 

責(zé)任編輯:龐桂玉 來(lái)源: 前端大全
相關(guān)推薦

2023-09-19 22:41:30

控制器HTTP

2021-01-18 05:13:04

TomcatHttp

2024-09-30 08:43:33

HttpgolangTimeout

2021-04-22 05:37:14

Axios 開(kāi)源項(xiàng)目HTTP 攔截器

2018-07-30 16:31:00

javascriptaxioshttp

2021-04-12 05:55:29

緩存數(shù)據(jù)Axios

2024-06-05 08:42:24

2024-03-19 08:36:19

2025-02-06 08:09:20

POSTGET數(shù)據(jù)

2021-04-06 06:01:11

AxiosWeb 項(xiàng)目開(kāi)發(fā)

2019-12-13 09:14:35

HTTP2協(xié)議

2024-04-30 09:53:12

axios架構(gòu)適配器

2024-08-12 12:32:53

Axios機(jī)制網(wǎng)絡(luò)

2021-07-23 15:55:31

HTTPETag前端

2021-05-26 05:18:51

HTTP ETag Entity Tag

2019-04-08 15:11:12

HTTP協(xié)議Web

2021-06-02 05:41:48

項(xiàng)目實(shí)踐Axiosaxios二次封裝

2018-10-18 10:05:43

HTTP網(wǎng)絡(luò)協(xié)議TCP

2018-07-24 13:01:52

前端優(yōu)化前端性能瀏覽器

2024-08-27 08:55:32

Axios底層網(wǎng)絡(luò)
點(diǎn)贊
收藏

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