const fetch = (url, options) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
const { status, readyState } = xhr
if (readyState === 1) return
if (status !== 200) return reject(xhr)
if (readyState === 4) {
return resolve(xhr)
}
}
xhr.onerror = () => {
reject(xhr)
}
const { method = 'GET', async = true, username, password, send, test, open, ...rest } = options
xhr.open(method, url, async, username, password)
for (const [key, value] of Object.entries(rest)) {
if (!(key in xhr)) {
return reject(`${key} is undefined, reference resources: https://www.w3school.com.cn/xmldom/dom_http.asp`)
}
if (typeof xhr[key] == 'function') {
const { arguments } = value;
if (!!arguments && (arguments.constructor === Array)) {
xhr[key](...value)
} else {
xhr[key](value)
}
} else {
xhr[key] = value
}
}
xhr.send(send)
})
};
const url = 'https://cdn.jsdelivr.net/gh/npm-for-cw/mockStaticFiles/simple2k13/png/isDICM.png'
const data = new FormData()
data.append('test', 1)
fetch(url, {
responseType: 'arraybuffer',
method: 'post',
send: data,
// send: { arguments: [1, 2, 34] }
})
.then(e => {
console.log(e)
}, error => {
console.log(error, 'error')
})
console