upload, string extensions, lgres
This commit is contained in:
@ -1,4 +1,7 @@
|
||||
function combineUrl(url) {
|
||||
if (/^(https?|wss?|ftp):/.test(url)) {
|
||||
return url;
|
||||
}
|
||||
if (typeof consts === 'undefined') {
|
||||
return url;
|
||||
}
|
||||
@ -11,7 +14,7 @@ function get(url, options) {
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
...options.customerHeaders,
|
||||
'Content-Type': options.contentType || 'application/json'
|
||||
'Accept': options.accept || 'application/json'
|
||||
},
|
||||
signal: options.signal,
|
||||
cache: 'default'
|
||||
@ -20,19 +23,62 @@ function get(url, options) {
|
||||
|
||||
function post(url, data, options) {
|
||||
options ??= {};
|
||||
// let contentType;
|
||||
if (data instanceof FormData) {
|
||||
// contentType = 'multipart/form-data';
|
||||
} else {
|
||||
if (typeof data !== 'string') {
|
||||
data = JSON.stringify(data);
|
||||
}
|
||||
// contentType = 'application/json';
|
||||
if (options.customerHeaders == null) {
|
||||
options.customerHeaders = {};
|
||||
}
|
||||
if (options.customerHeaders['Content-Type'] == null) {
|
||||
options.customerHeaders['Content-Type'] = 'application/json';
|
||||
}
|
||||
}
|
||||
return fetch(combineUrl(url), {
|
||||
method: options.method || 'POST',
|
||||
headers: {
|
||||
...options.customerHeaders,
|
||||
'Content-Type': options.contentType || 'application/json'
|
||||
},
|
||||
headers: options.customerHeaders,
|
||||
body: data,
|
||||
signal: options.signal,
|
||||
cache: 'no-cache'
|
||||
});
|
||||
}
|
||||
|
||||
function upload(url, data, options) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = new XMLHttpRequest();
|
||||
request.onreadystatechange = function () {
|
||||
if (this.readyState === XMLHttpRequest.DONE) {
|
||||
if (this.status === 200) {
|
||||
resolve(this);
|
||||
} else {
|
||||
reject(`${this.status} ${this.statusText}: ${this.responseText}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
options ??= {};
|
||||
if (typeof options.progress === 'function') {
|
||||
request.upload.addEventListener('progress', function (ev) {
|
||||
if (ev.lengthComputable) {
|
||||
options.progress.call(this, ev);
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
request.open('POST', combineUrl(url));
|
||||
if (options.customerHeaders != null) {
|
||||
for (let header of Object.entries(options.customerHeaders)) {
|
||||
request.setRequestHeader(header[0], header[1]);
|
||||
}
|
||||
}
|
||||
request.send(data);
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
get,
|
||||
post
|
||||
post,
|
||||
upload
|
||||
}
|
Reference in New Issue
Block a user