成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Axios Node 端請(qǐng)求是如何實(shí)現(xiàn)的?

開(kāi)發(fā) 前端
本文主要帶大家學(xué)習(xí)了 axios 的 Node 端實(shí)現(xiàn)。相比較于瀏覽器端要稍微復(fù)雜一些,不僅是因?yàn)槲覀円紤]請(qǐng)求可能的最大跳轉(zhuǎn)(maxRedirects),還要同時(shí)監(jiān)聽(tīng)請(qǐng)求實(shí)例以及響應(yīng)流數(shù)據(jù)上的事件,確保整個(gè)請(qǐng)求過(guò)程被完整監(jiān)聽(tīng)。
本文我們將討論 axios 的 Node 環(huán)境實(shí)現(xiàn)。我們都知道使用 axios 可以讓我們?cè)跒g覽器和 Node 端獲得一致的使用體驗(yàn)。這部分是通過(guò)適配器模式來(lái)實(shí)現(xiàn)的。

axios 內(nèi)置了 2 個(gè)適配器(截止到 v1.6.8 版本)[8]:xhr.js 和 http.js。

圖片圖片

顧名思義,xhr.js 是針對(duì)瀏覽器環(huán)境提供的 XMLHttpRequest 封裝的;http.js 則是針對(duì) Node 端的 http/https 模塊進(jìn)行封裝的。

不久前,我們?cè)敿?xì)講解了瀏覽器端的實(shí)現(xiàn),本文就來(lái)看看 Node 環(huán)境又是如何實(shí)現(xiàn)的。

Node 端請(qǐng)求案例

老規(guī)矩,在介紹實(shí)現(xiàn)之前,先看看 axios 在瀏覽器器環(huán)境的使用。

首先創(chuàng)建項(xiàng)目,安裝 axios 依賴:

mdir axios-demos
cd axios-demos
npm init
npm install axios
# 使用 VS Code 打開(kāi)當(dāng)前目錄
code .

寫一個(gè)測(cè)試文件 index.js:

// index.js
const axios = require('axios')

axios.get('https://httpstat.us/200')
  .then(res => {
    console.log('res >>>>', res)
  })

執(zhí)行文件:

node --watch index.js

注意:--watch[9] 是 Node.js 在 v16.19.0 版本引入的實(shí)驗(yàn)特性,在 v22.0.0 已轉(zhuǎn)為正式特性。

打印出來(lái)結(jié)果類似:

Restarting 'index.js'
res >>>> {
  status: 200,
  statusText: 'OK'
  headers: Object [AxiosHeaders] {}
  config: {}
  request: <ref *1> ClientRequest {}
  data: { code: 200, description: 'OK' }
}
Completed running 'index.js'

修改 Index.js 文件內(nèi)容保存:

const axios = require('axios')

axios.get('https://httpstat.us/404')
  .catch(err => {
    console.log('err >>>>', err)
  })

打印結(jié)果類似:

Restarting 'index.js'
err >>>> AxiosError: Request failed with status code 404 {
  code: 'ERR_BAD_REQUEST',
  config: {}
  request: <ref *1> ClientRequest {}
  response: {
    status: 404,
    statusText: 'Not Found',
    data: { code: 404, description: 'Not Found' }
  }
}

以上我們就算講完了 axios 在 Node 端的簡(jiǎn)單使用,這就是 axios 好處所在,統(tǒng)一的使用體驗(yàn),免去了我們?cè)诳缙脚_(tái)的學(xué)習(xí)成本,提升了開(kāi)發(fā)體驗(yàn)。

源碼分析

接下來(lái)就來(lái)看看 axios 的 Node 端實(shí)現(xiàn)。源代碼位于 lib/adapters/http.js[10] 下。

// /v1.6.8/lib/adapters/http.js#L160
export default isHttpAdapterSupported && function httpAdapter(config) {/* ... */}

Node 端發(fā)出的請(qǐng)求最終都是交由 httpAdapter(config) 函數(shù)處理的,其核心實(shí)現(xiàn)如下:

import http from 'http';
import https from 'https';

export default isHttpAdapterSupported && function httpAdapter(config) {
  // 1)
  return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
    
    // 2)
    let {data, lookup, family} = config;
    const {responseType, responseEncoding} = config;
    const method = config.method.toUpperCase();
    
    // Parse url
    const fullPath = buildFullPath(config.baseURL, config.url);
    const parsed = new URL(fullPath, 'http://localhost');
    
    const headers = AxiosHeaders.from(config.headers).normalize();
    
    if (data && !utils.isStream(data)) {
      if (Buffer.isBuffer(data)) {
        // Nothing to do...
      } else if (utils.isArrayBuffer(data)) {
        data = Buffer.from(new Uint8Array(data));
      } else if (utils.isString(data)) {
        data = Buffer.from(data, 'utf-8');
      } else {
        return reject(new AxiosError(
          'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
          AxiosError.ERR_BAD_REQUEST,
          config
        ));
      }
    }
    
    const options = {
      path,
      method: method,
      headers: headers.toJSON(),
      agents: { http: config.httpAgent, https: config.httpsAgent },
      auth,
      protocol,
      family,
      beforeRedirect: dispatchBeforeRedirect,
      beforeRedirects: {}
    };
    
    // 3)  
    let transport;
    const isHttpsRequest = /https:?/.test(options.protocol);
    
    if (config.maxRedirects === 0) {
      transport = isHttpsRequest ? https : http;
    }
    
    // Create the request
    req = transport.request(options, function handleResponse(res) {
      // ...
    }
    
    // 4)
    // Handle errors
    req.on('error', function handleRequestError(err) {
      // @todo remove
      // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
      reject(AxiosError.from(err, null, config, req));
    });
    
    // 5)
    // Handle request timeout
    if (config.timeout) {
      req.setTimeout(timeout, function handleRequestTimeout() {
        if (isDone) return;
        let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
        const transitional = config.transitional || transitionalDefaults;
        if (config.timeoutErrorMessage) {
          timeoutErrorMessage = config.timeoutErrorMessage;
        }
        reject(new AxiosError(
          timeoutErrorMessage,
          transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
          config,
          req
        ));
        abort();
      });
    }
    
    // 6)
    // Send the request
    if (utils.isStream(data)) {
      let ended = false;
      let errored = false;

      data.on('end', () => {
        ended = true;
      });

      data.once('error', err => {
        errored = true;
        req.destroy(err);
      });

      data.on('close', () => {
        if (!ended && !errored) {
          abort(new CanceledError('Request stream has been aborted', config, req));
        }
      });

      data.pipe(req);
    } else {
      req.end(data);
    }
  }

是有點(diǎn)長(zhǎng),但大概瀏覽一遍就行,后面會(huì)詳細(xì)講。實(shí)現(xiàn)主要有 6 部分:

  1. 這里的 wrapAsync 是對(duì) return new Promise((resolve, resolve) => {}) 的包裝,暴露出 resolve、reject 供 dispatchHttpRequest 函數(shù)內(nèi)部調(diào)用使用,代表請(qǐng)求成功或失敗
  2. 接下里,就是根據(jù)傳入的 config 信息組裝請(qǐng)求參數(shù) options 了
  3. axios 會(huì)根據(jù)傳入的 url 的協(xié)議,決定是采用 http 還是 https 模塊創(chuàng)建請(qǐng)求
  4. 監(jiān)聽(tīng)請(qǐng)求 req 上的異常(error)事件
  5. 跟 4) 一樣,不過(guò)監(jiān)聽(tīng)的是請(qǐng)求 req 上的超時(shí)事件。而其他諸如取消請(qǐng)求、完成請(qǐng)求等其他兼容事件則是在 2) 創(chuàng)建請(qǐng)求的回調(diào)函數(shù) handleResponse(res) 中處理的
  6. 最后,調(diào)用 req.end(data) 發(fā)送請(qǐng)求即可。當(dāng)然,這里會(huì)針對(duì) data 是 Stream 類型的情況特別處理一下

大概介紹了之后,我們?cè)偕钊朊恳徊骄唧w學(xué)習(xí)一下。

包裝函數(shù) wrapAsync

首先,httpAdapter(config) 內(nèi)部的實(shí)現(xiàn)是經(jīng)過(guò) wrapAsync 包裝函數(shù)返回的。

// /v1.6.8/lib/adapters/http.js#L122-L145
const wrapAsync = (asyncExecutor) => {
  return new Promise((resolve, reject) => {
    let onDone;
    let isDone;

    const done = (value, isRejected) => {
      if (isDone) return;
      isDone = true;
      onDone && onDone(value, isRejected);
    }

    const _resolve = (value) => {
      done(value);
      resolve(value);
    };

    const _reject = (reason) => {
      done(reason, true);
      reject(reason);
    }

    asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
  })
};

調(diào)用 wrapAsync 函數(shù)會(huì)返回一個(gè) Promise 對(duì)象,除了跟原生 Promise 構(gòu)造函數(shù)一樣會(huì)返回 resolve、reject 之外,還額外拓展了一個(gè) onDone 參數(shù),確保 Promise 狀態(tài)改變后,總是會(huì)調(diào)用 onDone。

組裝請(qǐng)求參數(shù)

在處理好返回值后,接下來(lái)要做的就是組裝請(qǐng)求參數(shù)了,請(qǐng)求參數(shù)最終會(huì)交由 http.request(options)[11]/https.request(options)[12] 處理,因此需要符合其類型定義。

http 模塊的請(qǐng)求案例

在理解 options 參數(shù)之前,先了解一下 http 模塊的請(qǐng)求案例。

const http = require('node:http');

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData),
  },
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

req.end(JSON.stringify({
  'msg': 'Hello World!',
}));

以上,我們向 http://www.google.com/upload 發(fā)起了一個(gè) POST 請(qǐng)求(https 請(qǐng)求與此類次)。

值得注意的是,請(qǐng)求參數(shù) options 中并不包含請(qǐng)求體數(shù)據(jù),請(qǐng)求體數(shù)據(jù)最終是以 req.end(data) 發(fā)動(dòng)出去的,這一點(diǎn)跟 XMLHttpRequest 實(shí)例的做法類似。

組裝請(qǐng)求參數(shù)

再來(lái)看看 axios 中關(guān)于這塊請(qǐng)求參數(shù)的組裝邏輯。

首先,使用 .baseURL 和 .url 參數(shù)解析出跟 URL 相關(guān)數(shù)據(jù)。

/v1.6.8/lib/adapters/http.js#L221
// Parse url
const fullPath = buildFullPath(config.baseURL, config.url);
const parsed = new URL(fullPath, 'http://localhost');
const protocol = parsed.protocol || supportedProtocols[0];

不支持的請(qǐng)求協(xié)議會(huì)報(bào)錯(cuò)。

// /v1.6.8/lib/platform/node/index.js#L11
protocols: [ 'http', 'https', 'file', 'data' ]
// /v1.6.8/lib/adapters/http.js#L44
const supportedProtocols = platform.protocols.map(protocol => {
  return protocol + ':';
});

// /v1.6.8/lib/adapters/http.js#L265-L271
if (supportedProtocols.indexOf(protocol) === -1) {
  return reject(new AxiosError(
    'Unsupported protocol ' + protocol,
    AxiosError.ERR_BAD_REQUEST,
    config
  ));
}

錯(cuò)誤 CODE 是 ERR_BAD_REQUEST,類似 4xx 錯(cuò)誤。

接下來(lái),將 headers 參數(shù)轉(zhuǎn)成 AxiosHeaders 實(shí)例。

// /v1.6.8/lib/adapters/http.js#L273
const headers = AxiosHeaders.from(config.headers).normalize();

最后,處理下請(qǐng)求體數(shù)據(jù) config.data。

// /v1.6.8/lib/adapters/http.js#L287-L326
// support for spec compliant FormData objects
if (utils.isSpecCompliantForm(data)) {
  const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);

  data = formDataToStream(data, (formHeaders) => {
    headers.set(formHeaders);
  }, {
    tag: `axios-${VERSION}-boundary`,
    boundary: userBoundary && userBoundary[1] || undefined
  });
  // support for https://www.npmjs.com/package/form-data api
} else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
  headers.set(data.getHeaders());

  if (!headers.hasContentLength()) {
    try {
      const knownLength = await util.promisify(data.getLength).call(data);
      Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
      /*eslint no-empty:0*/
    } catch (e) {
    }
  }
} else if (utils.isBlob(data)) {
  data.size && headers.setContentType(data.type || 'application/octet-stream');
  headers.setContentLength(data.size || 0);
  data = stream.Readable.from(readBlob(data));
} else if (data && !utils.isStream(data)) {
  if (Buffer.isBuffer(data)) {
    // Nothing to do...
  } else if (utils.isArrayBuffer(data)) {
    data = Buffer.from(new Uint8Array(data));
  } else if (utils.isString(data)) {
    data = Buffer.from(data, 'utf-8');
  } else {
    return reject(new AxiosError(
      'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
      AxiosError.ERR_BAD_REQUEST,
      config
    ));
  }

axios 會(huì)針對(duì)傳入的不同類型的 config.data 做統(tǒng)一處理,最終不是處理成 Stream 就是處理成 Buffer。

不過(guò),當(dāng)傳入的 data 是對(duì)象時(shí),在調(diào)用 httpAdapter(config) 之前,會(huì)先經(jīng)過(guò) transformRequest() 函數(shù)處理成字符串。

// /v1.6.8/lib/defaults/index.js#L91-L94
if (isObjectPayload || hasJSONContentType ) {
  headers.setContentType('application/json', false);
  return stringifySafely(data);
}

針對(duì)這個(gè)場(chǎng)景,data 會(huì)進(jìn)入到下面的處理邏輯,將字符串處理成 Buffer。

// /v1.6.8/lib/adapters/http.js#L287-L326
if (utils.isString(data)) {
  data = Buffer.from(data, 'utf-8');
}

然后,獲得請(qǐng)求路徑 path。

// /v1.6.8/lib/adapters/http.js#L384C4-L397C1
try {
  path = buildURL(
    parsed.pathname + parsed.search,
    config.params,
    config.paramsSerializer
  ).replace(/^\?/, '');
} catch (err) {
   // ...
}

最后,組裝 options 參數(shù)。

// /v1.6.8/lib/adapters/http.js#L403C1-L413C7
const options = {
  path,
  method: method,
  headers: headers.toJSON(),
  agents: { http: config.httpAgent, https: config.httpsAgent },
  auth,
  protocol,
  family,
  beforeRedirect: dispatchBeforeRedirect,
  beforeRedirects: {}
};

創(chuàng)建請(qǐng)求

再看創(chuàng)建請(qǐng)求環(huán)節(jié)。

獲得請(qǐng)求實(shí)例

首先,是獲得請(qǐng)求實(shí)例。

import followRedirects from 'follow-redirects';
const {http: httpFollow, https: httpsFollow} = followRedirects;

// /v1.6.8/lib/adapters/http.js#L426-L441
let transport;
const isHttpsRequest = isHttps.test(options.protocol);
options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
if (config.transport) {
  transport = config.transport;
} else if (config.maxRedirects === 0) {
  transport = isHttpsRequest ? https : http;
} else {
  if (config.maxRedirects) {
    options.maxRedirects = config.maxRedirects;
  }
  if (config.beforeRedirect) {
    options.beforeRedirects.config = config.beforeRedirect;
  }
  transport = isHttpsRequest ? httpsFollow : httpFollow;
}

如上所示,你可以通過(guò) config.transport 傳入,但通常不會(huì)這么做。否則,axios 內(nèi)部會(huì)根據(jù)你是否傳入 config.maxRedirects(默認(rèn) undefined) 決定使用原生 http/https 模塊還是 follow-redirects 包里提供的 http/https 方法。

如果沒(méi)有傳入 config.maxRedirects,axios 默認(rèn)會(huì)使用 follow-redirects 包里提供的 http/https 方法發(fā)起請(qǐng)求,它的用法跟原生 http/https 模塊一樣,這里甚至可以只使用 follow-redirects 就夠了。

創(chuàng)建請(qǐng)求

下面就是創(chuàng)建請(qǐng)求了。

// Create the request
req = transport.request(options, function handleResponse(res) {}

我們?cè)?handleResponse 回調(diào)函數(shù)里處理返回?cái)?shù)據(jù) res。

function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
function request(
    url: string | URL,
    options: RequestOptions,
    callback?: (res: IncomingMessage) => void,
): ClientRequest;

根據(jù)定義,我們知道 res 是 IncomingMessage 類型,繼承自 stream.Readable[13],是一種可讀的 Stream。

const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
});

res 的處理我們會(huì)放到處理請(qǐng)求一節(jié)講述,下面就是發(fā)出請(qǐng)求了。

發(fā)出請(qǐng)求

這部分代碼比較簡(jiǎn)單,而數(shù)據(jù)體也是在這里傳入的。

// /v1.6.8/lib/adapters/http.js#L658C5-L681C6
// Send the request
if (utils.isStream(data)) {
  let ended = false;
  let errored = false;

  data.on('end', () => {
    ended = true;
  });

  data.once('error', err => {
    errored = true;
    req.destroy(err);
  });

  data.on('close', () => {
    if (!ended && !errored) {
      abort(new CanceledError('Request stream has been aborted', config, req));
    }
  });

  data.pipe(req);
} else {
  req.end(data);
}

如果你的請(qǐng)求體是 Buffer 類型的,那么直接傳入 req.end(data) 即可,否則(Stream 類型)則需要以管道形式傳遞給 req。

處理請(qǐng)求

接著創(chuàng)建請(qǐng)求一節(jié),下面開(kāi)始分析請(qǐng)求的處理。

Node.js 部分的請(qǐng)求處理,比處理 XMLHttpRequest 稍微復(fù)雜一些。你要在 2 個(gè)地方做監(jiān)聽(tīng)處理。

  1. transport.request 返回的 req 實(shí)例
  2. 另一個(gè),則是 transport.request 回調(diào)函數(shù) handleResponse 返回的 res(也就是 responseStream)

監(jiān)聽(tīng) responseStream

首先,用 res/responseStream 上已有的信息組裝響應(yīng)數(shù)據(jù) response。

// /v1.6.8/lib/adapters/http.js#L478
// decompress the response body transparently if required
let responseStream = res;

// return the last request in case of redirects
const lastRequest = res.req || req;

const response = {
  status: res.statusCode,
  statusText: res.statusMessage,
  headers: new AxiosHeaders(res.headers),
  config,
  request: lastRequest
};

這是不完整的,因?yàn)槲覀冞€沒(méi)有設(shè)置 response.data。

// /v1.6.8/lib/adapters/http.js#L535C7-L538C15
if (responseType === 'stream') {
  response.data = responseStream;
  settle(resolve, reject, response);
} else {
  // ...
}

如果用戶需要的是響應(yīng)類型是 stream,那么一切就變得簡(jiǎn)單了,直接將數(shù)據(jù)都給 settle 函數(shù)即可。

// /v1.6.8/lib/core/settle.js
export default function settle(resolve, reject, response) {
  const validateStatus = response.config.validateStatus;
  if (!response.status || !validateStatus || validateStatus(response.status)) {
    resolve(response);
  } else {
    reject(new AxiosError(
      'Request failed with status code ' + response.status,
      [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
      response.config,
      response.request,
      response
    ));
  }
}

settle 函數(shù)會(huì)根據(jù)傳入的 response.status 和 config.validateStatus() 決定請(qǐng)求是成功(resolve)還是失敗(reject)。

當(dāng)然,如果需要的響應(yīng)類型不是 stream,就監(jiān)聽(tīng) responseStream 對(duì)象上的事件,處理請(qǐng)求結(jié)果。

// /v1.6.8/lib/adapters/http.js#L538C1-L591C8
} else {
  const responseBuffer = [];
  let totalResponseBytes = 0;

  // 1)
  responseStream.on('data', function handleStreamData(chunk) {
    responseBuffer.push(chunk);
    totalResponseBytes += chunk.length;

    // make sure the content length is not over the maxContentLength if specified
    if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
      // stream.destroy() emit aborted event before calling reject() on Node.js v16
      rejected = true;
      responseStream.destroy();
      reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
        AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
    }
  });
  
  // 2)
  responseStream.on('aborted', function handlerStreamAborted() {
    if (rejected) {
      return;
    }

    const err = new AxiosError(
      'maxContentLength size of ' + config.maxContentLength + ' exceeded',
      AxiosError.ERR_BAD_RESPONSE,
      config,
      lastRequest
    );
    responseStream.destroy(err);
    reject(err);
  });

  // 3)
  responseStream.on('error', function handleStreamError(err) {
    if (req.destroyed) return;
    reject(AxiosError.from(err, null, config, lastRequest));
  });
  
  // 4)
  responseStream.on('end', function handleStreamEnd() {
    try {
      let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
      if (responseType !== 'arraybuffer') {
        responseData = responseData.toString(responseEncoding);
        if (!responseEncoding || responseEncoding === 'utf8') {
          responseData = utils.stripBOM(responseData);
        }
      }
      response.data = responseData;
    } catch (err) {
      return reject(AxiosError.from(err, null, config, response.request, response));
    }
    settle(resolve, reject, response);
  });
}

responseStream 上會(huì)監(jiān)聽(tīng) 4 個(gè)事件。

  1. data:Node 請(qǐng)求的響應(yīng)默認(rèn)都是以流數(shù)據(jù)形式接收的,而 data 就是在接收過(guò)程中會(huì)不斷觸發(fā)的事件。我們?cè)谶@里將接收到的數(shù)據(jù)存儲(chǔ)在 responseBuffer 中,以便后續(xù)使用
  2. aborted:會(huì)在接收響應(yīng)數(shù)據(jù)超過(guò)時(shí),或是調(diào)用 .destory() 時(shí)觸發(fā)
  3. err:在流數(shù)據(jù)接收錯(cuò)誤時(shí)調(diào)用
  4. end:數(shù)據(jù)結(jié)束接收,將收集到的 responseBuffer 先轉(zhuǎn)換成 Buffer 類型,再轉(zhuǎn)換成字符串,最終賦值給 response.data

監(jiān)聽(tīng) req

以上,我們完成了對(duì)響應(yīng)數(shù)據(jù)的監(jiān)聽(tīng)。我們?cè)賮?lái)看看,對(duì)請(qǐng)求實(shí)例 req 的監(jiān)聽(tīng)。

// /v1.6.8/lib/adapters/http.js#L606
// Handle errors
req.on('error', function handleRequestError(err) {
  // @todo remove
  // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
  reject(AxiosError.from(err, null, config, req));
});

// /v1.6.8/lib/adapters/http.js#L619
// Handle request timeout
if (config.timeout) {
  req.setTimeout(timeout, function handleRequestTimeout() {
    if (isDone) return;
    let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
    const transitional = config.transitional || transitionalDefaults;
    if (config.timeoutErrorMessage) {
      timeoutErrorMessage = config.timeoutErrorMessage;
    }
    reject(new AxiosError(
      timeoutErrorMessage,
      transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
      config,
      req
    ));
    abort();
  });
}

一共監(jiān)聽(tīng)了 2 個(gè)事件:

  1. error:請(qǐng)求出錯(cuò)
  2. req.setTimeout():請(qǐng)求超時(shí)

以上,我們就完成了請(qǐng)求處理的所有內(nèi)容。可以發(fā)現(xiàn),Node 端處理請(qǐng)求的邏輯會(huì)比瀏覽器端稍微復(fù)雜一些:你需要同時(shí)監(jiān)聽(tīng)請(qǐng)求實(shí)例以及響應(yīng)流數(shù)據(jù)上的事件,確保整個(gè)請(qǐng)求過(guò)程被完整監(jiān)聽(tīng)。

總結(jié)

本文主要帶大家學(xué)習(xí)了 axios 的 Node 端實(shí)現(xiàn)。

相比較于瀏覽器端要稍微復(fù)雜一些,不僅是因?yàn)槲覀円紤]請(qǐng)求可能的最大跳轉(zhuǎn)(maxRedirects),還要同時(shí)監(jiān)聽(tīng)請(qǐng)求實(shí)例以及響應(yīng)流數(shù)據(jù)上的事件,確保整個(gè)請(qǐng)求過(guò)程被完整監(jiān)聽(tīng)。

參考資料

[1]axios 是如何實(shí)現(xiàn)取消請(qǐng)求的?: https://juejin.cn/post/7359444013894811689

[2]你知道嗎?axios 請(qǐng)求是 JSON 響應(yīng)優(yōu)先的: https://juejin.cn/post/7359580605320036415

[3]axios 跨端架構(gòu)是如何實(shí)現(xiàn)的?: https://juejin.cn/post/7362119848660451391

[4]axios 攔截器機(jī)制是如何實(shí)現(xiàn)的?: https://juejin.cn/post/7363545737874161703

[5]axios 瀏覽器端請(qǐng)求是如何實(shí)現(xiàn)的?: https://juejin.cn/post/7363928569028821029

[6]axios 對(duì)外出口API是如何設(shè)計(jì)的?: https://juejin.cn/post/7364614337371308071

[7]axios 中是如何處理異常的?: https://juejin.cn/post/7369951085194739775

[8]axios 內(nèi)置了 2 個(gè)適配器(截止到 v1.6.8 版本): https://github.com/axios/axios/tree/v1.6.8/lib/adapters

[9]--watch: https://nodejs.org/api/cli.html#--watch

[10]lib/adapters/http.js: https://github.com/axios/axios/blob/v1.6.8/lib/adapters/http.js

[11]http.request(options): https://nodejs.org/docs/latest/api/http.html#httprequestoptions-callback

[12]https.request(options): https://nodejs.org/docs/latest/api/https.html#httpsrequestoptions-callback

[13]stream.Readable: https://nodejs.org/docs/latest/api/stream.html#class-streamreadable

責(zé)任編輯:武曉燕 來(lái)源: 寫代碼的寶哥
相關(guān)推薦

2021-04-22 05:37:14

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

2024-04-30 09:53:12

axios架構(gòu)適配器

2019-08-20 08:56:18

Linux設(shè)計(jì)數(shù)據(jù)庫(kù)

2019-09-20 09:12:03

服務(wù)器互聯(lián)網(wǎng)TCP

2021-07-27 14:50:15

axiosHTTP前端

2021-04-12 05:55:29

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

2021-04-06 06:01:11

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

2020-11-12 09:55:02

OAuth2

2023-10-04 07:35:03

2021-12-02 07:25:58

ASP.NET CorAjax請(qǐng)求

2024-08-12 12:32:53

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

2018-07-30 16:31:00

javascriptaxioshttp

2022-10-19 09:27:39

2024-08-27 08:55:32

Axios底層網(wǎng)絡(luò)

2022-09-02 10:20:44

網(wǎng)絡(luò)切片網(wǎng)絡(luò)5G

2022-02-22 11:17:31

Kafka架構(gòu)代碼

2018-04-22 00:01:43

JavaScript Node 語(yǔ)言

2022-01-28 14:20:53

前端代碼中斷

2021-08-20 09:50:41

Web指紋前端

2021-03-09 08:03:21

Node.js 線程JavaScript
點(diǎn)贊
收藏

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

主站蜘蛛池模板: 99只有精品| 一区视频在线免费观看 | 久久夜视频 | 成人精品久久久 | 精品久久精品 | 91久久精品一区二区二区 | 一区二区在线不卡 | 男人电影天堂 | 中文一区二区视频 | www九色 | 99视频在线免费观看 | 精品乱码一区二区三四区 | 91麻豆精品国产91久久久资源速度 | 97视频久久 | 爱爱免费视频 | 欧美激情第一区 | 91视频精选 | 中文字幕国产视频 | 欧美一级片在线看 | 99热在线观看精品 | 国产在线观看一区二区三区 | 色爱综合网 | 国产免费视频 | 99re6热在线精品视频播放 | 黑人巨大精品 | www.色综合| 欧美激情视频网站 | 中国黄色在线视频 | www.久| 国产精品国产a级 | 奇米超碰| 香蕉一区 | 亚洲国产成人精品女人久久久 | 中文字幕成人av | 亚洲成人一区 | 国产精品亚洲成在人线 | 日本黄色影片在线观看 | 久久久av一区 | 国产精品一区在线 | 69堂永久69tangcom | 久久精品一区 |