mirror of
https://github.com/tenrok/axios.git
synced 2026-06-17 19:21:29 +03:00
Added data URL support for node.js; (#4725)
* Added data URL support for node.js; Added missed data URL protocol for the browser environment; Optimized JSON parsing in the default response transformer; Refactored project structure; Added `cause` prop for AxiosError instance that refers to the original error if it was wrapped with `AxiosError.from` method; Added fromDataURI helper; Added test for handling data:url as an `arraybuffer|text|stream`; * Added throwing of 405 HTTP error if the method is not GET;
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
var AxiosError = require('../core/AxiosError');
|
||||
var parseProtocol = require('./parseProtocol');
|
||||
var platform = require('../platform');
|
||||
|
||||
var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
|
||||
|
||||
/**
|
||||
* Parse data uri to a Buffer or Blob
|
||||
* @param {String} uri
|
||||
* @param {?Boolean} asBlob
|
||||
* @param {?Object} options
|
||||
* @param {?Function} options.Blob
|
||||
* @returns {Buffer|Blob}
|
||||
*/
|
||||
module.exports = function fromDataURI(uri, asBlob, options) {
|
||||
var _Blob = options && options.Blob || platform.classes.Blob;
|
||||
var protocol = parseProtocol(uri);
|
||||
|
||||
if (asBlob === undefined && _Blob) {
|
||||
asBlob = true;
|
||||
}
|
||||
|
||||
if (protocol === 'data') {
|
||||
uri = uri.slice(protocol.length);
|
||||
|
||||
var match = DATA_URL_PATTERN.exec(uri);
|
||||
|
||||
if (!match) {
|
||||
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
|
||||
}
|
||||
|
||||
var mime = match[1];
|
||||
var isBase64 = match[2];
|
||||
var body = match[3];
|
||||
var buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
|
||||
|
||||
if (asBlob) {
|
||||
if (!_Blob) {
|
||||
throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
|
||||
}
|
||||
|
||||
return new _Blob([buffer], {type: mime});
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
|
||||
};
|
||||
Reference in New Issue
Block a user