http.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. 'use strict';
  2. import utils from './../utils.js';
  3. import settle from './../core/settle.js';
  4. import buildFullPath from '../core/buildFullPath.js';
  5. import buildURL from './../helpers/buildURL.js';
  6. import proxyFromEnv from 'proxy-from-env';
  7. import http from 'http';
  8. import https from 'https';
  9. import util from 'util';
  10. import followRedirects from 'follow-redirects';
  11. import zlib from 'zlib';
  12. import {VERSION} from '../env/data.js';
  13. import transitionalDefaults from '../defaults/transitional.js';
  14. import AxiosError from '../core/AxiosError.js';
  15. import CanceledError from '../cancel/CanceledError.js';
  16. import platform from '../platform/index.js';
  17. import fromDataURI from '../helpers/fromDataURI.js';
  18. import stream from 'stream';
  19. import AxiosHeaders from '../core/AxiosHeaders.js';
  20. import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
  21. import {EventEmitter} from 'events';
  22. import formDataToStream from "../helpers/formDataToStream.js";
  23. import readBlob from "../helpers/readBlob.js";
  24. import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';
  25. import callbackify from "../helpers/callbackify.js";
  26. import {progressEventReducer, progressEventDecorator, asyncDecorator} from "../helpers/progressEventReducer.js";
  27. const zlibOptions = {
  28. flush: zlib.constants.Z_SYNC_FLUSH,
  29. finishFlush: zlib.constants.Z_SYNC_FLUSH
  30. };
  31. const brotliOptions = {
  32. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  33. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
  34. }
  35. const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
  36. const {http: httpFollow, https: httpsFollow} = followRedirects;
  37. const isHttps = /https:?/;
  38. const supportedProtocols = platform.protocols.map(protocol => {
  39. return protocol + ':';
  40. });
  41. const flushOnFinish = (stream, [throttled, flush]) => {
  42. stream
  43. .on('end', flush)
  44. .on('error', flush);
  45. return throttled;
  46. }
  47. /**
  48. * If the proxy or config beforeRedirects functions are defined, call them with the options
  49. * object.
  50. *
  51. * @param {Object<string, any>} options - The options object that was passed to the request.
  52. *
  53. * @returns {Object<string, any>}
  54. */
  55. function dispatchBeforeRedirect(options, responseDetails) {
  56. if (options.beforeRedirects.proxy) {
  57. options.beforeRedirects.proxy(options);
  58. }
  59. if (options.beforeRedirects.config) {
  60. options.beforeRedirects.config(options, responseDetails);
  61. }
  62. }
  63. /**
  64. * If the proxy or config afterRedirects functions are defined, call them with the options
  65. *
  66. * @param {http.ClientRequestArgs} options
  67. * @param {AxiosProxyConfig} configProxy configuration from Axios options object
  68. * @param {string} location
  69. *
  70. * @returns {http.ClientRequestArgs}
  71. */
  72. function setProxy(options, configProxy, location) {
  73. let proxy = configProxy;
  74. if (!proxy && proxy !== false) {
  75. const proxyUrl = proxyFromEnv.getProxyForUrl(location);
  76. if (proxyUrl) {
  77. proxy = new URL(proxyUrl);
  78. }
  79. }
  80. if (proxy) {
  81. // Basic proxy authorization
  82. if (proxy.username) {
  83. proxy.auth = (proxy.username || '') + ':' + (proxy.password || '');
  84. }
  85. if (proxy.auth) {
  86. // Support proxy auth object form
  87. if (proxy.auth.username || proxy.auth.password) {
  88. proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
  89. }
  90. const base64 = Buffer
  91. .from(proxy.auth, 'utf8')
  92. .toString('base64');
  93. options.headers['Proxy-Authorization'] = 'Basic ' + base64;
  94. }
  95. options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
  96. const proxyHost = proxy.hostname || proxy.host;
  97. options.hostname = proxyHost;
  98. // Replace 'host' since options is not a URL object
  99. options.host = proxyHost;
  100. options.port = proxy.port;
  101. options.path = location;
  102. if (proxy.protocol) {
  103. options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`;
  104. }
  105. }
  106. options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
  107. // Configure proxy for redirected request, passing the original config proxy to apply
  108. // the exact same logic as if the redirected request was performed by axios directly.
  109. setProxy(redirectOptions, configProxy, redirectOptions.href);
  110. };
  111. }
  112. const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process';
  113. // temporary hotfix
  114. const wrapAsync = (asyncExecutor) => {
  115. return new Promise((resolve, reject) => {
  116. let onDone;
  117. let isDone;
  118. const done = (value, isRejected) => {
  119. if (isDone) return;
  120. isDone = true;
  121. onDone && onDone(value, isRejected);
  122. }
  123. const _resolve = (value) => {
  124. done(value);
  125. resolve(value);
  126. };
  127. const _reject = (reason) => {
  128. done(reason, true);
  129. reject(reason);
  130. }
  131. asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
  132. })
  133. };
  134. const resolveFamily = ({address, family}) => {
  135. if (!utils.isString(address)) {
  136. throw TypeError('address must be a string');
  137. }
  138. return ({
  139. address,
  140. family: family || (address.indexOf('.') < 0 ? 6 : 4)
  141. });
  142. }
  143. const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family});
  144. /*eslint consistent-return:0*/
  145. export default isHttpAdapterSupported && function httpAdapter(config) {
  146. return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
  147. let {data, lookup, family} = config;
  148. const {responseType, responseEncoding} = config;
  149. const method = config.method.toUpperCase();
  150. let isDone;
  151. let rejected = false;
  152. let req;
  153. if (lookup) {
  154. const _lookup = callbackify(lookup, (value) => utils.isArray(value) ? value : [value]);
  155. // hotfix to support opt.all option which is required for node 20.x
  156. lookup = (hostname, opt, cb) => {
  157. _lookup(hostname, opt, (err, arg0, arg1) => {
  158. if (err) {
  159. return cb(err);
  160. }
  161. const addresses = utils.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
  162. opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
  163. });
  164. }
  165. }
  166. // temporary internal emitter until the AxiosRequest class will be implemented
  167. const emitter = new EventEmitter();
  168. const onFinished = () => {
  169. if (config.cancelToken) {
  170. config.cancelToken.unsubscribe(abort);
  171. }
  172. if (config.signal) {
  173. config.signal.removeEventListener('abort', abort);
  174. }
  175. emitter.removeAllListeners();
  176. }
  177. onDone((value, isRejected) => {
  178. isDone = true;
  179. if (isRejected) {
  180. rejected = true;
  181. onFinished();
  182. }
  183. });
  184. function abort(reason) {
  185. emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
  186. }
  187. emitter.once('abort', reject);
  188. if (config.cancelToken || config.signal) {
  189. config.cancelToken && config.cancelToken.subscribe(abort);
  190. if (config.signal) {
  191. config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
  192. }
  193. }
  194. // Parse url
  195. const fullPath = buildFullPath(config.baseURL, config.url);
  196. const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined);
  197. const protocol = parsed.protocol || supportedProtocols[0];
  198. if (protocol === 'data:') {
  199. let convertedData;
  200. if (method !== 'GET') {
  201. return settle(resolve, reject, {
  202. status: 405,
  203. statusText: 'method not allowed',
  204. headers: {},
  205. config
  206. });
  207. }
  208. try {
  209. convertedData = fromDataURI(config.url, responseType === 'blob', {
  210. Blob: config.env && config.env.Blob
  211. });
  212. } catch (err) {
  213. throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
  214. }
  215. if (responseType === 'text') {
  216. convertedData = convertedData.toString(responseEncoding);
  217. if (!responseEncoding || responseEncoding === 'utf8') {
  218. convertedData = utils.stripBOM(convertedData);
  219. }
  220. } else if (responseType === 'stream') {
  221. convertedData = stream.Readable.from(convertedData);
  222. }
  223. return settle(resolve, reject, {
  224. data: convertedData,
  225. status: 200,
  226. statusText: 'OK',
  227. headers: new AxiosHeaders(),
  228. config
  229. });
  230. }
  231. if (supportedProtocols.indexOf(protocol) === -1) {
  232. return reject(new AxiosError(
  233. 'Unsupported protocol ' + protocol,
  234. AxiosError.ERR_BAD_REQUEST,
  235. config
  236. ));
  237. }
  238. const headers = AxiosHeaders.from(config.headers).normalize();
  239. // Set User-Agent (required by some servers)
  240. // See https://github.com/axios/axios/issues/69
  241. // User-Agent is specified; handle case where no UA header is desired
  242. // Only set header if it hasn't been set in config
  243. headers.set('User-Agent', 'axios/' + VERSION, false);
  244. const {onUploadProgress, onDownloadProgress} = config;
  245. const maxRate = config.maxRate;
  246. let maxUploadRate = undefined;
  247. let maxDownloadRate = undefined;
  248. // support for spec compliant FormData objects
  249. if (utils.isSpecCompliantForm(data)) {
  250. const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
  251. data = formDataToStream(data, (formHeaders) => {
  252. headers.set(formHeaders);
  253. }, {
  254. tag: `axios-${VERSION}-boundary`,
  255. boundary: userBoundary && userBoundary[1] || undefined
  256. });
  257. // support for https://www.npmjs.com/package/form-data api
  258. } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
  259. headers.set(data.getHeaders());
  260. if (!headers.hasContentLength()) {
  261. try {
  262. const knownLength = await util.promisify(data.getLength).call(data);
  263. Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
  264. /*eslint no-empty:0*/
  265. } catch (e) {
  266. }
  267. }
  268. } else if (utils.isBlob(data) || utils.isFile(data)) {
  269. data.size && headers.setContentType(data.type || 'application/octet-stream');
  270. headers.setContentLength(data.size || 0);
  271. data = stream.Readable.from(readBlob(data));
  272. } else if (data && !utils.isStream(data)) {
  273. if (Buffer.isBuffer(data)) {
  274. // Nothing to do...
  275. } else if (utils.isArrayBuffer(data)) {
  276. data = Buffer.from(new Uint8Array(data));
  277. } else if (utils.isString(data)) {
  278. data = Buffer.from(data, 'utf-8');
  279. } else {
  280. return reject(new AxiosError(
  281. 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
  282. AxiosError.ERR_BAD_REQUEST,
  283. config
  284. ));
  285. }
  286. // Add Content-Length header if data exists
  287. headers.setContentLength(data.length, false);
  288. if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
  289. return reject(new AxiosError(
  290. 'Request body larger than maxBodyLength limit',
  291. AxiosError.ERR_BAD_REQUEST,
  292. config
  293. ));
  294. }
  295. }
  296. const contentLength = utils.toFiniteNumber(headers.getContentLength());
  297. if (utils.isArray(maxRate)) {
  298. maxUploadRate = maxRate[0];
  299. maxDownloadRate = maxRate[1];
  300. } else {
  301. maxUploadRate = maxDownloadRate = maxRate;
  302. }
  303. if (data && (onUploadProgress || maxUploadRate)) {
  304. if (!utils.isStream(data)) {
  305. data = stream.Readable.from(data, {objectMode: false});
  306. }
  307. data = stream.pipeline([data, new AxiosTransformStream({
  308. maxRate: utils.toFiniteNumber(maxUploadRate)
  309. })], utils.noop);
  310. onUploadProgress && data.on('progress', flushOnFinish(
  311. data,
  312. progressEventDecorator(
  313. contentLength,
  314. progressEventReducer(asyncDecorator(onUploadProgress), false, 3)
  315. )
  316. ));
  317. }
  318. // HTTP basic authentication
  319. let auth = undefined;
  320. if (config.auth) {
  321. const username = config.auth.username || '';
  322. const password = config.auth.password || '';
  323. auth = username + ':' + password;
  324. }
  325. if (!auth && parsed.username) {
  326. const urlUsername = parsed.username;
  327. const urlPassword = parsed.password;
  328. auth = urlUsername + ':' + urlPassword;
  329. }
  330. auth && headers.delete('authorization');
  331. let path;
  332. try {
  333. path = buildURL(
  334. parsed.pathname + parsed.search,
  335. config.params,
  336. config.paramsSerializer
  337. ).replace(/^\?/, '');
  338. } catch (err) {
  339. const customErr = new Error(err.message);
  340. customErr.config = config;
  341. customErr.url = config.url;
  342. customErr.exists = true;
  343. return reject(customErr);
  344. }
  345. headers.set(
  346. 'Accept-Encoding',
  347. 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false
  348. );
  349. const options = {
  350. path,
  351. method: method,
  352. headers: headers.toJSON(),
  353. agents: { http: config.httpAgent, https: config.httpsAgent },
  354. auth,
  355. protocol,
  356. family,
  357. beforeRedirect: dispatchBeforeRedirect,
  358. beforeRedirects: {}
  359. };
  360. // cacheable-lookup integration hotfix
  361. !utils.isUndefined(lookup) && (options.lookup = lookup);
  362. if (config.socketPath) {
  363. options.socketPath = config.socketPath;
  364. } else {
  365. options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
  366. options.port = parsed.port;
  367. setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
  368. }
  369. let transport;
  370. const isHttpsRequest = isHttps.test(options.protocol);
  371. options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
  372. if (config.transport) {
  373. transport = config.transport;
  374. } else if (config.maxRedirects === 0) {
  375. transport = isHttpsRequest ? https : http;
  376. } else {
  377. if (config.maxRedirects) {
  378. options.maxRedirects = config.maxRedirects;
  379. }
  380. if (config.beforeRedirect) {
  381. options.beforeRedirects.config = config.beforeRedirect;
  382. }
  383. transport = isHttpsRequest ? httpsFollow : httpFollow;
  384. }
  385. if (config.maxBodyLength > -1) {
  386. options.maxBodyLength = config.maxBodyLength;
  387. } else {
  388. // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
  389. options.maxBodyLength = Infinity;
  390. }
  391. if (config.insecureHTTPParser) {
  392. options.insecureHTTPParser = config.insecureHTTPParser;
  393. }
  394. // Create the request
  395. req = transport.request(options, function handleResponse(res) {
  396. if (req.destroyed) return;
  397. const streams = [res];
  398. const responseLength = +res.headers['content-length'];
  399. if (onDownloadProgress || maxDownloadRate) {
  400. const transformStream = new AxiosTransformStream({
  401. maxRate: utils.toFiniteNumber(maxDownloadRate)
  402. });
  403. onDownloadProgress && transformStream.on('progress', flushOnFinish(
  404. transformStream,
  405. progressEventDecorator(
  406. responseLength,
  407. progressEventReducer(asyncDecorator(onDownloadProgress), true, 3)
  408. )
  409. ));
  410. streams.push(transformStream);
  411. }
  412. // decompress the response body transparently if required
  413. let responseStream = res;
  414. // return the last request in case of redirects
  415. const lastRequest = res.req || req;
  416. // if decompress disabled we should not decompress
  417. if (config.decompress !== false && res.headers['content-encoding']) {
  418. // if no content, but headers still say that it is encoded,
  419. // remove the header not confuse downstream operations
  420. if (method === 'HEAD' || res.statusCode === 204) {
  421. delete res.headers['content-encoding'];
  422. }
  423. switch ((res.headers['content-encoding'] || '').toLowerCase()) {
  424. /*eslint default-case:0*/
  425. case 'gzip':
  426. case 'x-gzip':
  427. case 'compress':
  428. case 'x-compress':
  429. // add the unzipper to the body stream processing pipeline
  430. streams.push(zlib.createUnzip(zlibOptions));
  431. // remove the content-encoding in order to not confuse downstream operations
  432. delete res.headers['content-encoding'];
  433. break;
  434. case 'deflate':
  435. streams.push(new ZlibHeaderTransformStream());
  436. // add the unzipper to the body stream processing pipeline
  437. streams.push(zlib.createUnzip(zlibOptions));
  438. // remove the content-encoding in order to not confuse downstream operations
  439. delete res.headers['content-encoding'];
  440. break;
  441. case 'br':
  442. if (isBrotliSupported) {
  443. streams.push(zlib.createBrotliDecompress(brotliOptions));
  444. delete res.headers['content-encoding'];
  445. }
  446. }
  447. }
  448. responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
  449. const offListeners = stream.finished(responseStream, () => {
  450. offListeners();
  451. onFinished();
  452. });
  453. const response = {
  454. status: res.statusCode,
  455. statusText: res.statusMessage,
  456. headers: new AxiosHeaders(res.headers),
  457. config,
  458. request: lastRequest
  459. };
  460. if (responseType === 'stream') {
  461. response.data = responseStream;
  462. settle(resolve, reject, response);
  463. } else {
  464. const responseBuffer = [];
  465. let totalResponseBytes = 0;
  466. responseStream.on('data', function handleStreamData(chunk) {
  467. responseBuffer.push(chunk);
  468. totalResponseBytes += chunk.length;
  469. // make sure the content length is not over the maxContentLength if specified
  470. if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
  471. // stream.destroy() emit aborted event before calling reject() on Node.js v16
  472. rejected = true;
  473. responseStream.destroy();
  474. reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
  475. AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
  476. }
  477. });
  478. responseStream.on('aborted', function handlerStreamAborted() {
  479. if (rejected) {
  480. return;
  481. }
  482. const err = new AxiosError(
  483. 'stream has been aborted',
  484. AxiosError.ERR_BAD_RESPONSE,
  485. config,
  486. lastRequest
  487. );
  488. responseStream.destroy(err);
  489. reject(err);
  490. });
  491. responseStream.on('error', function handleStreamError(err) {
  492. if (req.destroyed) return;
  493. reject(AxiosError.from(err, null, config, lastRequest));
  494. });
  495. responseStream.on('end', function handleStreamEnd() {
  496. try {
  497. let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
  498. if (responseType !== 'arraybuffer') {
  499. responseData = responseData.toString(responseEncoding);
  500. if (!responseEncoding || responseEncoding === 'utf8') {
  501. responseData = utils.stripBOM(responseData);
  502. }
  503. }
  504. response.data = responseData;
  505. } catch (err) {
  506. return reject(AxiosError.from(err, null, config, response.request, response));
  507. }
  508. settle(resolve, reject, response);
  509. });
  510. }
  511. emitter.once('abort', err => {
  512. if (!responseStream.destroyed) {
  513. responseStream.emit('error', err);
  514. responseStream.destroy();
  515. }
  516. });
  517. });
  518. emitter.once('abort', err => {
  519. reject(err);
  520. req.destroy(err);
  521. });
  522. // Handle errors
  523. req.on('error', function handleRequestError(err) {
  524. // @todo remove
  525. // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
  526. reject(AxiosError.from(err, null, config, req));
  527. });
  528. // set tcp keep alive to prevent drop connection by peer
  529. req.on('socket', function handleRequestSocket(socket) {
  530. // default interval of sending ack packet is 1 minute
  531. socket.setKeepAlive(true, 1000 * 60);
  532. });
  533. // Handle request timeout
  534. if (config.timeout) {
  535. // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
  536. const timeout = parseInt(config.timeout, 10);
  537. if (Number.isNaN(timeout)) {
  538. reject(new AxiosError(
  539. 'error trying to parse `config.timeout` to int',
  540. AxiosError.ERR_BAD_OPTION_VALUE,
  541. config,
  542. req
  543. ));
  544. return;
  545. }
  546. // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
  547. // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
  548. // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
  549. // And then these socket which be hang up will devouring CPU little by little.
  550. // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
  551. req.setTimeout(timeout, function handleRequestTimeout() {
  552. if (isDone) return;
  553. let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
  554. const transitional = config.transitional || transitionalDefaults;
  555. if (config.timeoutErrorMessage) {
  556. timeoutErrorMessage = config.timeoutErrorMessage;
  557. }
  558. reject(new AxiosError(
  559. timeoutErrorMessage,
  560. transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
  561. config,
  562. req
  563. ));
  564. abort();
  565. });
  566. }
  567. // Send the request
  568. if (utils.isStream(data)) {
  569. let ended = false;
  570. let errored = false;
  571. data.on('end', () => {
  572. ended = true;
  573. });
  574. data.once('error', err => {
  575. errored = true;
  576. req.destroy(err);
  577. });
  578. data.on('close', () => {
  579. if (!ended && !errored) {
  580. abort(new CanceledError('Request stream has been aborted', config, req));
  581. }
  582. });
  583. data.pipe(req);
  584. } else {
  585. req.end(data);
  586. }
  587. });
  588. }
  589. export const __setProxy = setProxy;