diff --git a/lib/adapters/fetch.js b/lib/adapters/fetch.js index cf1c680..c569982 100644 --- a/lib/adapters/fetch.js +++ b/lib/adapters/fetch.js @@ -18,8 +18,9 @@ const fetchProgressDecorator = (total, fn) => { } const isFetchSupported = typeof fetch !== 'undefined'; +const isReadableStreamSupported = isFetchSupported && typeof ReadableStream !== 'undefined'; -const supportsRequestStreams = isFetchSupported && (() => { +const supportsRequestStream = isReadableStreamSupported && (() => { let duplexAccessed = false; const hasContentType = new Request(platform.origin, { @@ -36,15 +37,26 @@ const supportsRequestStreams = isFetchSupported && (() => { const DEFAULT_CHUNK_SIZE = 64 * 1024; +const supportsResponseStream = isReadableStreamSupported && !!(()=> { + try { + return utils.isReadableStream(new Response('').body); + } catch(err) { + // return undefined + } +})(); + const resolvers = { - stream: (res) => res.body + stream: supportsResponseStream && ((res) => res.body) }; -isFetchSupported && ['text', 'arrayBuffer', 'blob', 'formData'].forEach(type => [ - resolvers[type] = utils.isFunction(Response.prototype[type]) ? (res) => res[type]() : (_, config) => { - throw new AxiosError(`Response type ${type} is not supported`, AxiosError.ERR_NOT_SUPPORT, config); - } -]) +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(utils.isBlob(body)) { @@ -74,7 +86,7 @@ const resolveBodyLength = async (headers, body) => { return length == null ? getBodyLength(body) : length; } -export default async (config) => { +export default isFetchSupported && (async (config) => { let { url, method, @@ -106,7 +118,7 @@ export default async (config) => { } try { - if (onUploadProgress && supportsRequestStreams && method !== 'get' && method !== 'head') { + if (onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head') { let requestContentLength = await resolveBodyLength(headers, data); let _request = new Request(url, { @@ -145,7 +157,7 @@ export default async (config) => { const isStreamResponse = responseType === 'stream' || responseType === 'response'; - if (onDownloadProgress || isStreamResponse) { + if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) { const options = {}; Object.getOwnPropertyNames(response).forEach(prop => { @@ -192,6 +204,6 @@ export default async (config) => { throw AxiosError.from(err, code, config, request); } -} +}); diff --git a/package.json b/package.json index 46f751a..82c8ef4 100644 --- a/package.json +++ b/package.json @@ -216,4 +216,4 @@ "@commitlint/config-conventional" ] } -} \ No newline at end of file +}