AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

Axios 跨端架構是如何實現的?

來源: 責編: 時間:2024-05-07 09:15:51 199觀看
導讀我們都知道,axios 是是一個跨平臺請求方案,在瀏覽器端采用 XMLHttpRequest API 進行封裝,而在 Node.js 端則采用 http/https 模塊進行封裝。axios 內部采用適配器模式將二者合二為一,在隱藏了底層的實現的同時,又對外開放

我們都知道,axios 是是一個跨平臺請求方案,在瀏覽器端采用 XMLHttpRequest API 進行封裝,而在 Node.js 端則采用 http/https 模塊進行封裝。axios 內部采用適配器模式將二者合二為一,在隱藏了底層的實現的同時,又對外開放了一套統一的開放接口。GfY28資訊網——每日最新資訊28at.com

那么本文,我們將來探討這個話題:axios 的跨端架構是如何實現的?GfY28資訊網——每日最新資訊28at.com

從 axios 發送請求說起

我們先來看看 axios 是如何發送請求的。GfY28資訊網——每日最新資訊28at.com

// 發送一個 GET 請求axios({   method: 'get',  url: 'https://jsonplaceholder.typicode.com/comments'  params: { postId: 1 }}) // 發送一個 POST 請求axios({  method: 'post'  url: 'https://jsonplaceholder.typicode.com/posts',  data: {    title: 'foo',    body: 'bar',    userId: 1,  }})

dispatchRequest() 方法

當使用 axios 請求時,實際上內部是由 Axios[3] 實例的 .request() 方法處理的。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/core/Axios.js#L38async request(configOrUrl, config) {    try {      return await this._request(configOrUrl, config);    } catch (err) {}}

而 ._request() 方法內部會先將  configOrUrl, config 2 個參數處理成 config 參數。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/core/Axios.js#L62_request(configOrUrl, config) {    if (typeof configOrUrl === 'string') {      config = config || {};      config.url = configOrUrl;    } else {      config = configOrUrl || {};    }    // ...}

這里是為了同時兼容下面 2 種調用方法。GfY28資訊網——每日最新資訊28at.com

// 調用方式一axios('https://jsonplaceholder.typicode.com/posts/1')// 調用方式二axios({  method: 'get',  url: 'https://jsonplaceholder.typicode.com/posts/1'})

當然,這不是重點。在 ._request() 方法內部請求最終會交由 dispatchRequest() 處理。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/core/Axios.js#L169-L173try {  promise = dispatchRequest.call(this, newConfig);} catch (error) {  return Promise.reject(error);}

dispatchRequest() 是實際調用請求的地方,而實際調用是采用  XMLHttpRequest API(瀏覽器)還是http/https 模塊(Node.js),則需要進一步查看。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/core/dispatchRequest.js#L34export default function dispatchRequest(config) { /* ... */ }

dispatchRequest() 接收的是上一步合并之后的 config 參數,有了這個參數我們就可以發送請求了。GfY28資訊網——每日最新資訊28at.com

跨端適配實現

// /v1.6.8/lib/core/dispatchRequest.js#L49const adapter = adapters.getAdapter(config.adapter || defaults.adapter);

這里就是我們所說的 axios 內部所使用的適配器模式了。GfY28資訊網——每日最新資訊28at.com

axios 支持從外出傳入 adapter 參數支持自定義請求能力的實現,不過很少使用。大部分請求下,我們都是使用內置的適配器實現。GfY28資訊網——每日最新資訊28at.com

defaults.adapter

defaults.adapter 的值如下:GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/defaults/index.js#L40adapter: ['xhr', 'http'],

adapters.getAdapter(['xhr', 'http']) 又是在做什么事情呢?GfY28資訊網——每日最新資訊28at.com

適配器實現

首先,adapters 位于 lib/adapters/adapters.js[4]。GfY28資訊網——每日最新資訊28at.com

所屬的目錄結構如下:GfY28資訊網——每日最新資訊28at.com

圖片圖片GfY28資訊網——每日最新資訊28at.com

可以看到針對瀏覽器和 Node.js 2 個環境的適配支持:http.js、xhr.js。GfY28資訊網——每日最新資訊28at.com

adapters 的實現如下。GfY28資訊網——每日最新資訊28at.com

首先,將內置的 2 個適配文件引入。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/adapters/adapters.js#L2-L9import httpAdapter from './http.js';import xhrAdapter from './xhr.js';const knownAdapters = {  http: httpAdapter,  xhr: xhrAdapter}

knownAdapters 的屬性名正好是和 defaults.adapter 的值 ['xhr', 'http'] 是一一對應的。GfY28資訊網——每日最新資訊28at.com

而 adapters.getAdapter(['xhr', 'http']) 的實現是這樣的:GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/adapters/adapters.js#L27-L75export default {  getAdapter: (adapters) => {    // 1)    adapters = Array.isArray(adapters) ? adapters : [adapters];    let nameOrAdapter;    let adapter;        // 2)    for (let i = 0; i < adapters.length; i++) {      nameOrAdapter = adapters[i];      adapter = nameOrAdapter;            // 3)      if (!isResolvedHandle(nameOrAdapter)) {        adapter = knownAdapters[String(nameOrAdapter).toLowerCase()];      }      if (adapter) {        break;      }    }    // 4)    if (!adapter) {      throw new AxiosError(        `There is no suitable adapter to dispatch the request `,        'ERR_NOT_SUPPORT'      );    }    return adapter;  }}

內容比較長,我們會按照代碼標準的序號分 4 個部分來講。GfY28資訊網——每日最新資訊28at.com

1)這里是為了兼容調用 axios() 時傳入 adapter 參數的情況。GfY28資訊網——每日最新資訊28at.com

// `adapter` allows custom handling of requests which makes testing easier.// Return a promise and supply a valid response (see lib/adapters/README.md).adapter: function (config) {  /* ... */},

因為接下來 adapters 是作為數組處理,所以這種場景下,我們將 adapter 封裝成數組 [adapters]。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/adapters/adapters.js#L28adapters = Array.isArray(adapters) ? adapters : [adapters];

2)接下來,就是遍歷 adapters 找到要用的那個適配器。GfY28資訊網——每日最新資訊28at.com

到目前為止,adapters[i](也就是下面的 nameOrAdapter)既可能是字符串('xhr'、'http'),也可能是函數(function (config) {})。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/adapters/adapters.js#L37let nameOrAdapter = adapters[i];adapter = nameOrAdapter;

3)那么,我們還要檢查 nameOrAdapter 的類型。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/adapters/adapters.js#L42-L48if (!isResolvedHandle(nameOrAdapter)) {  adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];}

isResolvedHandle() 是一個工具函數,其目的是為了判斷是否要從 knownAdapters 獲取適配器。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/adapters/adapters.js#L24const isResolvedHandle = (adapter) => typeof adapter === 'function' || adapter === null || adapter === false;

簡單理解,只有 adapter 是字符串的情況('xhr' 或 'http'),isResolvedHandle(nameOrAdapter) 才返回 false,才從 knownAdapters 獲得適配器。GfY28資訊網——每日最新資訊28at.com

typeof adapter === 'function' || adapter === null 這個判斷條件我們容易理解,這是為了排除自定義 adapter 參數(傳入函數或 null)的情況。GfY28資訊網——每日最新資訊28at.com

而 adapter === false 又是對應什么情況呢?GfY28資訊網——每日最新資訊28at.com

那是因為我們的代碼只可能是在瀏覽器或 Node.js 環境下運行。這個時候 httpAdapter 和 xhrAdapter 具體返回是有差異的。GfY28資訊網——每日最新資訊28at.com

// /v1.6.8/lib/adapters/xhr.js#L48const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';export default isXHRAdapterSupported && function (config) {/* ...*/}// /v1.6.8/lib/adapters/http.js#L160const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process';export default isHttpAdapterSupported && function httpAdapter(config) {/* ... */}

也就是說:在瀏覽器環境 httpAdapter 返回 false,xhrAdapter 返回函數;在 Node.js 環境 xhrAdapter 返回 false,httpAdapter 返回函數。GfY28資訊網——每日最新資訊28at.com

因此,一旦 isResolvedHandle() 邏輯執行完成后。GfY28資訊網——每日最新資訊28at.com

if (!isResolvedHandle(nameOrAdapter)) {/* ... */}

會檢查 adapter 變量的值,一旦有值(非 false)就說明找到適配器了,結束遍歷。GfY28資訊網——每日最新資訊28at.com

if (adapter) {  break;}

4)最終在返回適配器前做空檢查GfY28資訊網——每日最新資訊28at.com

// 4)if (!adapter) {  throw new AxiosError(    `There is no suitable adapter to dispatch the request `,    'ERR_NOT_SUPPORT'  );}return adapter;

如此,就完成了跨端架構的實現。GfY28資訊網——每日最新資訊28at.com

總結

本文我們講述了 axios 的跨端架構原理。axios 內部實際發出請求是通過 dispatchRequest() 方法處理的,再往里看則是通過適配器模式取得適應于當前環境的適配器函數。GfY28資訊網——每日最新資訊28at.com

axios 內置了 2 個適配器支持:httpAdapter 和 xhrAdapter。httpAdapter 是 Node.js 環境實現,通過 http/https 模塊;xhrAdapter 這是瀏覽器環境實現,通過 XMLHttpRequest API 實現。Node.js 環境 xhrAdapter 返回 false,瀏覽器環境 httpAdapter 返回 false——這樣總是能返回正確的適配器。GfY28資訊網——每日最新資訊28at.com

參考資料

[1]axios 是如何實現取消請求的?: https://juejin.cn/post/7359444013894811689GfY28資訊網——每日最新資訊28at.com

[2]你知道嗎?axios 請求是 JSON 響應優先的: https://juejin.cn/post/7359580605320036415GfY28資訊網——每日最新資訊28at.com

[3]Axios: https://github.com/axios/axios/blob/v1.6.8/lib/core/Axios.jsGfY28資訊網——每日最新資訊28at.com

[4]lib/adapters/adapters.js: https://github.com/axios/axios/blob/v1.6.8/lib/adapters/adapters.jsGfY28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-87048-0.htmlAxios 跨端架構是如何實現的?

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 盤點Lombok的幾個操作,你記住了嗎?

下一篇: Python 網絡爬蟲利器:執行 JavaScript 實現數據抓取

標簽:
  • 熱門焦點
  • 一加Ace2 Pro官宣:普及16G內存 引領24G

    一加官方今天繼續為本月發布的新機一加Ace2 Pro帶來預熱,公布了內存方面的信息。“淘汰 8GB ,12GB 起步,16GB 普及,24GB 引領,還有呢?#一加Ace2Pro#,2023 年 8 月,敬請期待。”同時
  • K60至尊版剛預熱 一加Ace2 Pro正面硬剛

    Redmi這邊剛如火如荼的宣傳了K60 Ultra的各種技術和硬件配置,作為競品的一加也坐不住了。一加中國區總裁李杰發布了兩條微博,表示在自家的一加Ace2上早就已經采用了和PixelWo
  • 小米官宣:2023年上半年出貨量中國第一!

    今日早間,小米電視官方微博帶來消息,稱2023年小米電視上半年出貨量達到了中國第一,同時還表示小米電視的巨屏風暴即將開始。“公布一個好消息2023年#小米電視上半年出貨量中國
  • 多線程開發帶來的問題與解決方法

    使用多線程主要會帶來以下幾個問題:(一)線程安全問題  線程安全問題指的是在某一線程從開始訪問到結束訪問某一數據期間,該數據被其他的線程所修改,那么對于當前線程而言,該線程
  • 零售大模型“干中學”,攀爬數字化珠峰

    文/侯煜編輯/cc來源/華爾街科技眼對于絕大多數登山愛好者而言,攀爬珠穆朗瑪峰可謂終極目標。攀登珠峰的商業路線有兩條,一是尼泊爾境內的南坡路線,一是中國境內的北坡路線。相
  • Temu起訴SHEIN,跨境電商戰事升級

    來源 | 伯虎財經(bohuFN)作者 | 陳平安日前據外媒報道,拼多多旗下跨境電商平臺Temu正對競爭對手SHEIN提起新訴訟,訴狀稱Shein&ldquo;利用市場支配力量強迫服裝廠商與之簽訂獨家
  • 小米公益基金會捐贈2500萬元馳援北京、河北暴雨救災

    8月2日消息,今日小米科技創始人雷軍在其微博上發布消息稱,小米公益基金會宣布捐贈2500萬元馳援北京、河北暴雨救災。攜手抗災,京冀安康!以下為公告原文
  • iQOO Neo8系列今日官宣:首發天璣9200+ 全球安卓最強芯!

    在昨日舉行的的聯發科新一代旗艦芯片天璣9200+的發布會上,iQOO官方也正式宣布,全新的iQOO Neo8系列新品將全球首發搭載這款當前性能最強大的移動平臺
  • iQOO Neo8 Pro真機諜照曝光:天璣9200+和V1+旗艦雙芯加持

    去年10月,iQOO推出了iQOO Neo7系列機型,不僅搭載了天璣9000+,而且是同價位唯一一款天璣9000+直屏旗艦,一經上市便受到了用戶的廣泛關注。在時隔半年后,
Top