1
0
forked from dyf/APP

优化首页的下拉刷新、数据排序、绑定后刷新

This commit is contained in:
liub
2025-12-24 10:52:28 +08:00
parent 425b7b9cfd
commit 637658a762
202 changed files with 5432 additions and 301514 deletions

View File

@ -1,79 +1,126 @@
import utils from '../utils.js';
import httpAdapter from './http.js';
import xhrAdapter from './xhr.js';
import fetchAdapter from './fetch.js';
import * as fetchAdapter from './fetch.js';
import AxiosError from "../core/AxiosError.js";
/**
* Known adapters mapping.
* Provides environment-specific adapters for Axios:
* - `http` for Node.js
* - `xhr` for browsers
* - `fetch` for fetch API-based requests
*
* @type {Object<string, Function|Object>}
*/
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: fetchAdapter
}
fetch: {
get: fetchAdapter.getFetch,
}
};
// Assign adapter names for easier debugging and identification
utils.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
Object.defineProperty(fn, 'name', {value});
Object.defineProperty(fn, 'name', { value });
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', {value});
Object.defineProperty(fn, 'adapterName', { value });
}
});
/**
* Render a rejection reason string for unknown or unsupported adapters
*
* @param {string} reason
* @returns {string}
*/
const renderReason = (reason) => `- ${reason}`;
/**
* Check if the adapter is resolved (function, null, or false)
*
* @param {Function|null|false} adapter
* @returns {boolean}
*/
const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;
export default {
getAdapter: (adapters) => {
adapters = utils.isArray(adapters) ? adapters : [adapters];
/**
* Get the first suitable adapter from the provided list.
* Tries each adapter in order until a supported one is found.
* Throws an AxiosError if no adapter is suitable.
*
* @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
* @param {Object} config - Axios request configuration
* @throws {AxiosError} If no suitable adapter is available
* @returns {Function} The resolved adapter function
*/
function getAdapter(adapters, config) {
adapters = utils.isArray(adapters) ? adapters : [adapters];
const {length} = adapters;
let nameOrAdapter;
let adapter;
const { length } = adapters;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter = nameOrAdapter;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError(`Unknown adapter '${id}'`);
}
if (adapter === undefined) {
throw new AxiosError(`Unknown adapter '${id}'`);
}
if (adapter) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
if (adapter && (utils.isFunction(adapter) || (adapter = adapter.get(config)))) {
break;
}
const reasons = Object.entries(rejectedReasons)
.map(([id, state]) => `adapter ${id} ` +
(state === false ? 'is not supported by the environment' : 'is not available in the build')
);
rejectedReasons[id || '#' + i] = adapter;
}
let s = length ?
(reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
'as no adapter specified';
throw new AxiosError(
`There is no suitable adapter to dispatch the request ` + s,
'ERR_NOT_SUPPORT'
if (!adapter) {
const reasons = Object.entries(rejectedReasons)
.map(([id, state]) => `adapter ${id} ` +
(state === false ? 'is not supported by the environment' : 'is not available in the build')
);
}
return adapter;
},
adapters: knownAdapters
let s = length ?
(reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
'as no adapter specified';
throw new AxiosError(
`There is no suitable adapter to dispatch the request ` + s,
'ERR_NOT_SUPPORT'
);
}
return adapter;
}
/**
* Exports Axios adapters and utility to resolve an adapter
*/
export default {
/**
* Resolve an adapter from a list of adapter names or functions.
* @type {Function}
*/
getAdapter,
/**
* Exposes all known adapters
* @type {Object<string, Function|Object>}
*/
adapters: knownAdapters
};

View File

@ -8,14 +8,18 @@ import {progressEventReducer, progressEventDecorator, asyncDecorator} from "../h
import resolveConfig from "../helpers/resolveConfig.js";
import settle from "../core/settle.js";
const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const {isFunction} = utils;
const globalFetchAPI = (({Request, Response}) => ({
Request, Response
}))(utils.global);
const {
ReadableStream, TextEncoder
} = utils.global;
// used only inside the fetch adapter
const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
async (str) => new Uint8Array(await new Response(str).arrayBuffer())
);
const test = (fn, ...args) => {
try {
@ -25,205 +29,260 @@ const test = (fn, ...args) => {
}
}
const supportsRequestStream = isReadableStreamSupported && test(() => {
let duplexAccessed = false;
const factory = (env) => {
env = utils.merge.call({
skipUndefined: true
}, globalFetchAPI, env);
const hasContentType = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
}).headers.has('Content-Type');
const {fetch: envFetch, Request, Response} = env;
const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
const isRequestSupported = isFunction(Request);
const isResponseSupported = isFunction(Response);
return duplexAccessed && !hasContentType;
});
if (!isFetchSupported) {
return false;
}
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
const supportsResponseStream = isReadableStreamSupported &&
test(() => utils.isReadableStream(new Response('').body));
const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
async (str) => new Uint8Array(await new Request(str).arrayBuffer())
);
const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
let duplexAccessed = false;
const resolvers = {
stream: supportsResponseStream && ((res) => res.body)
};
const hasContentType = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
}).headers.has('Content-Type');
return duplexAccessed && !hasContentType;
});
const supportsResponseStream = isResponseSupported && isReadableStreamSupported &&
test(() => utils.isReadableStream(new Response('').body));
const resolvers = {
stream: supportsResponseStream && ((res) => res.body)
};
isFetchSupported && ((() => {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
!resolvers[type] && (resolvers[type] = (res, config) => {
let method = res && res[type];
if (method) {
return method.call(res);
}
isFetchSupported && (((res) => {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
!resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :
(_, config) => {
throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
})
});
})(new Response));
const getBodyLength = async (body) => {
if (body == null) {
return 0;
}
if(utils.isBlob(body)) {
return body.size;
}
if(utils.isSpecCompliantForm(body)) {
const _request = new Request(platform.origin, {
method: 'POST',
body,
});
return (await _request.arrayBuffer()).byteLength;
}
})());
if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {
return body.byteLength;
}
const getBodyLength = async (body) => {
if (body == null) {
return 0;
}
if(utils.isURLSearchParams(body)) {
body = body + '';
}
if (utils.isBlob(body)) {
return body.size;
}
if(utils.isString(body)) {
return (await encodeText(body)).byteLength;
}
}
const resolveBodyLength = async (headers, body) => {
const length = utils.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
}
export default isFetchSupported && (async (config) => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions
} = resolveConfig(config);
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
let request;
const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
composedSignal.unsubscribe();
});
let requestContentLength;
try {
if (
onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
(requestContentLength = await resolveBodyLength(headers, data)) !== 0
) {
let _request = new Request(url, {
if (utils.isSpecCompliantForm(body)) {
const _request = new Request(platform.origin, {
method: 'POST',
body: data,
duplex: "half"
body,
});
let contentTypeHeader;
if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader)
}
if (_request.body) {
const [onProgress, flush] = progressEventDecorator(
requestContentLength,
progressEventReducer(asyncDecorator(onUploadProgress))
);
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
}
return (await _request.arrayBuffer()).byteLength;
}
if (!utils.isString(withCredentials)) {
withCredentials = withCredentials ? 'include' : 'omit';
if (utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {
return body.byteLength;
}
// Cloudflare Workers throws when credentials are defined
// see https://github.com/cloudflare/workerd/issues/902
const isCredentialsSupported = "credentials" in Request.prototype;
request = new Request(url, {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: headers.normalize().toJSON(),
body: data,
duplex: "half",
credentials: isCredentialsSupported ? withCredentials : undefined
if (utils.isURLSearchParams(body)) {
body = body + '';
}
if (utils.isString(body)) {
return (await encodeText(body)).byteLength;
}
}
const resolveBodyLength = async (headers, body) => {
const length = utils.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
}
return async (config) => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions
} = resolveConfig(config);
let _fetch = envFetch || fetch;
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
let request = null;
const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
composedSignal.unsubscribe();
});
let response = await fetch(request);
let requestContentLength;
const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
try {
if (
onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
(requestContentLength = await resolveBodyLength(headers, data)) !== 0
) {
let _request = new Request(url, {
method: 'POST',
body: data,
duplex: "half"
});
if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
const options = {};
let contentTypeHeader;
['status', 'statusText', 'headers'].forEach(prop => {
options[prop] = response[prop];
});
const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));
const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
responseContentLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true)
) || [];
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}),
options
);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);
!isStreamResponse && unsubscribe && unsubscribe();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request
})
})
} catch (err) {
unsubscribe && unsubscribe();
if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
throw Object.assign(
new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
{
cause: err.cause || err
if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader)
}
)
if (_request.body) {
const [onProgress, flush] = progressEventDecorator(
requestContentLength,
progressEventReducer(asyncDecorator(onUploadProgress))
);
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
}
}
if (!utils.isString(withCredentials)) {
withCredentials = withCredentials ? 'include' : 'omit';
}
// Cloudflare Workers throws when credentials are defined
// see https://github.com/cloudflare/workerd/issues/902
const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
const resolvedOptions = {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: headers.normalize().toJSON(),
body: data,
duplex: "half",
credentials: isCredentialsSupported ? withCredentials : undefined
};
request = isRequestSupported && new Request(url, resolvedOptions);
let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
const options = {};
['status', 'statusText', 'headers'].forEach(prop => {
options[prop] = response[prop];
});
const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));
const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
responseContentLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true)
) || [];
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}),
options
);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);
!isStreamResponse && unsubscribe && unsubscribe();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request
})
})
} catch (err) {
unsubscribe && unsubscribe();
if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
throw Object.assign(
new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
{
cause: err.cause || err
}
)
}
throw AxiosError.from(err, err && err.code, config, request);
}
throw AxiosError.from(err, err && err.code, config, request);
}
});
}
const seedCache = new Map();
export const getFetch = (config) => {
let env = (config && config.env) || {};
const {fetch, Request, Response} = env;
const seeds = [
Request, Response, fetch
];
let len = seeds.length, i = len,
seed, target, map = seedCache;
while (i--) {
seed = seeds[i];
target = map.get(seed);
target === undefined && map.set(seed, target = (i ? new Map() : factory(env)))
map = target;
}
return target;
};
const adapter = getFetch();
export default adapter;

View File

@ -1,5 +1,3 @@
'use strict';
import utils from './../utils.js';
import settle from './../core/settle.js';
import buildFullPath from '../core/buildFullPath.js';
@ -7,6 +5,7 @@ import buildURL from './../helpers/buildURL.js';
import proxyFromEnv from 'proxy-from-env';
import http from 'http';
import https from 'https';
import http2 from 'http2';
import util from 'util';
import followRedirects from 'follow-redirects';
import zlib from 'zlib';
@ -25,6 +24,7 @@ import readBlob from "../helpers/readBlob.js";
import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';
import callbackify from "../helpers/callbackify.js";
import {progressEventReducer, progressEventDecorator, asyncDecorator} from "../helpers/progressEventReducer.js";
import estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js';
const zlibOptions = {
flush: zlib.constants.Z_SYNC_FLUSH,
@ -46,6 +46,7 @@ const supportedProtocols = platform.protocols.map(protocol => {
return protocol + ':';
});
const flushOnFinish = (stream, [throttled, flush]) => {
stream
.on('end', flush)
@ -54,6 +55,102 @@ const flushOnFinish = (stream, [throttled, flush]) => {
return throttled;
}
class Http2Sessions {
constructor() {
this.sessions = Object.create(null);
}
getSession(authority, options) {
options = Object.assign({
sessionTimeout: 1000
}, options);
let authoritySessions = this.sessions[authority];
if (authoritySessions) {
let len = authoritySessions.length;
for (let i = 0; i < len; i++) {
const [sessionHandle, sessionOptions] = authoritySessions[i];
if (!sessionHandle.destroyed && !sessionHandle.closed && util.isDeepStrictEqual(sessionOptions, options)) {
return sessionHandle;
}
}
}
const session = http2.connect(authority, options);
let removed;
const removeSession = () => {
if (removed) {
return;
}
removed = true;
let entries = authoritySessions, len = entries.length, i = len;
while (i--) {
if (entries[i][0] === session) {
if (len === 1) {
delete this.sessions[authority];
} else {
entries.splice(i, 1);
}
return;
}
}
};
const originalRequestFn = session.request;
const {sessionTimeout} = options;
if(sessionTimeout != null) {
let timer;
let streamsCount = 0;
session.request = function () {
const stream = originalRequestFn.apply(this, arguments);
streamsCount++;
if (timer) {
clearTimeout(timer);
timer = null;
}
stream.once('close', () => {
if (!--streamsCount) {
timer = setTimeout(() => {
timer = null;
removeSession();
}, sessionTimeout);
}
});
return stream;
}
}
session.once('close', removeSession);
let entry = [
session,
options
];
authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
return session;
}
}
const http2Sessions = new Http2Sessions();
/**
* If the proxy or config beforeRedirects functions are defined, call them with the options
* object.
@ -165,16 +262,75 @@ const resolveFamily = ({address, family}) => {
const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family});
const http2Transport = {
request(options, cb) {
const authority = options.protocol + '//' + options.hostname + ':' + (options.port || 80);
const {http2Options, headers} = options;
const session = http2Sessions.getSession(authority, http2Options);
const {
HTTP2_HEADER_SCHEME,
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS
} = http2.constants;
const http2Headers = {
[HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''),
[HTTP2_HEADER_METHOD]: options.method,
[HTTP2_HEADER_PATH]: options.path,
}
utils.forEach(headers, (header, name) => {
name.charAt(0) !== ':' && (http2Headers[name] = header);
});
const req = session.request(http2Headers);
req.once('response', (responseHeaders) => {
const response = req; //duplex
responseHeaders = Object.assign({}, responseHeaders);
const status = responseHeaders[HTTP2_HEADER_STATUS];
delete responseHeaders[HTTP2_HEADER_STATUS];
response.headers = responseHeaders;
response.statusCode = +status;
cb(response);
})
return req;
}
}
/*eslint consistent-return:0*/
export default isHttpAdapterSupported && function httpAdapter(config) {
return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
let {data, lookup, family} = config;
let {data, lookup, family, httpVersion = 1, http2Options} = config;
const {responseType, responseEncoding} = config;
const method = config.method.toUpperCase();
let isDone;
let rejected = false;
let req;
httpVersion = +httpVersion;
if (Number.isNaN(httpVersion)) {
throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
}
if (httpVersion !== 1 && httpVersion !== 2) {
throw TypeError(`Unsupported protocol version '${httpVersion}'`);
}
const isHttp2 = httpVersion === 2;
if (lookup) {
const _lookup = callbackify(lookup, (value) => utils.isArray(value) ? value : [value]);
// hotfix to support opt.all option which is required for node 20.x
@ -191,8 +347,17 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
}
}
// temporary internal emitter until the AxiosRequest class will be implemented
const emitter = new EventEmitter();
const abortEmitter = new EventEmitter();
function abort(reason) {
try {
abortEmitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
} catch(err) {
console.warn('emit error', err);
}
}
abortEmitter.once('abort', reject);
const onFinished = () => {
if (config.cancelToken) {
@ -203,23 +368,9 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
config.signal.removeEventListener('abort', abort);
}
emitter.removeAllListeners();
abortEmitter.removeAllListeners();
}
onDone((value, isRejected) => {
isDone = true;
if (isRejected) {
rejected = true;
onFinished();
}
});
function abort(reason) {
emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
}
emitter.once('abort', reject);
if (config.cancelToken || config.signal) {
config.cancelToken && config.cancelToken.subscribe(abort);
if (config.signal) {
@ -227,12 +378,52 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
}
}
onDone((response, isRejected) => {
isDone = true;
if (isRejected) {
rejected = true;
onFinished();
return;
}
const {data} = response;
if (data instanceof stream.Readable || data instanceof stream.Duplex) {
const offListeners = stream.finished(data, () => {
offListeners();
onFinished();
});
} else {
onFinished();
}
});
// Parse url
const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined);
const protocol = parsed.protocol || supportedProtocols[0];
if (protocol === 'data:') {
// Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
if (config.maxContentLength > -1) {
// Use the exact string passed to fromDataURI (config.url); fall back to fullPath if needed.
const dataUrl = String(config.url || fullPath || '');
const estimated = estimateDataURLDecodedBytes(dataUrl);
if (estimated > config.maxContentLength) {
return reject(new AxiosError(
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config
));
}
}
let convertedData;
if (method !== 'GET') {
@ -418,7 +609,8 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
protocol,
family,
beforeRedirect: dispatchBeforeRedirect,
beforeRedirects: {}
beforeRedirects: {},
http2Options
};
// cacheable-lookup integration hotfix
@ -435,18 +627,23 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
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;
if (isHttp2) {
transport = http2Transport;
} else {
if (config.maxRedirects) {
options.maxRedirects = config.maxRedirects;
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;
}
if (config.beforeRedirect) {
options.beforeRedirects.config = config.beforeRedirect;
}
transport = isHttpsRequest ? httpsFollow : httpFollow;
}
if (config.maxBodyLength > -1) {
@ -466,7 +663,7 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
const streams = [res];
const responseLength = +res.headers['content-length'];
const responseLength = utils.toFiniteNumber(res.headers['content-length']);
if (onDownloadProgress || maxDownloadRate) {
const transformStream = new AxiosTransformStream({
@ -529,10 +726,7 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
const offListeners = stream.finished(responseStream, () => {
offListeners();
onFinished();
});
const response = {
status: res.statusCode,
@ -558,7 +752,7 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
// 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',
abort(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
}
});
@ -600,7 +794,7 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
});
}
emitter.once('abort', err => {
abortEmitter.once('abort', err => {
if (!responseStream.destroyed) {
responseStream.emit('error', err);
responseStream.destroy();
@ -608,9 +802,12 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
});
});
emitter.once('abort', err => {
reject(err);
req.destroy(err);
abortEmitter.once('abort', err => {
if (req.close) {
req.close();
} else {
req.destroy(err);
}
});
// Handle errors
@ -632,7 +829,7 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
const timeout = parseInt(config.timeout, 10);
if (Number.isNaN(timeout)) {
reject(new AxiosError(
abort(new AxiosError(
'error trying to parse `config.timeout` to int',
AxiosError.ERR_BAD_OPTION_VALUE,
config,
@ -654,14 +851,16 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(new AxiosError(
abort(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
req
));
abort();
});
} else {
// explicitly reset the socket timeout value for a possible `keep-alive` request
req.setTimeout(0);
}
@ -687,7 +886,8 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
data.pipe(req);
} else {
req.end(data);
data && req.write(data);
req.end();
}
});
}

View File

@ -104,15 +104,18 @@ export default isXHRAdapterSupported && function (config) {
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
// Clean up request
request = null;
request.onerror = function handleError(event) {
// Browsers deliver a ProgressEvent in XHR onerror
// (message may be empty; when present, surface it)
// See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
const msg = event && event.message ? event.message : 'Network Error';
const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
// attach the underlying event for consumers who want details
err.event = event || null;
reject(err);
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';