原生http请求封装

满血复活,今天开始开始更新博客。
随着es6的普遍应用,promise属性也随之用之普遍,我们在一些项目中,为了避免引入一些http库,节省空间,就简单将原生http请求做了封装处理,封装代码如下:
(其中应用到了fetch,不懂得同学可以去mdn了解一下)
import http from './http';

let Http = {

    /**
* @example
* ```js
* Http.get('http://xxx.com/some_api', {
* headers: 'Instance of Header',
* mode: '请求模式 cors、 no-cors 或者 same-origin',
* })```
*
* @param {String} url
* @param {Object} opt
*/
get(url, opt) {
opt = opt || {};
opt.method = 'GET';
return fetch(url, opt);
}, /**
*
* @example
* ```js
* Http.post('http://xxx.com/some_api', {
* headers: 'Instance of Header',
* mode: '请求模式 cors、 no-cors 或者 same-origin',
* body: '字符串 查询字符串 FormData实例 Blob 或者 BufferSource(2进制数组)'
* })```
* @param {String} url
* @param {String | URLSearchParams | FormData | Blob | ArrayBuffer} data
* @param {Object} opt
*/
post(url, data, opt) {
opt = opt || {};
opt.method = 'POST';
let param;
if (data instanceof FormData || data instanceof URLSearchParams || typeof(data) === 'string') {
param = data;
} else {
param = new URLSearchParams();
for (let k in data) {
param.append(k, data[k]);
}
}
opt.body = param;
return fetch(url, opt);
}, /**
* @example
* ```js
* Http.upload('http://xxx.com/some_api', {
* progress: (loaded, total)=>{
* console.log(loaded, total);
* }
* })```
*
*
* @param {String} url
* @param {FormData | Blob | ArrayBuffer} data
* @param {Object} opt
*/
upload(url, data, opt) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onprogress = opt.progress;
xhr.onerror = reject;
xhr.timeout = reject;
xhr.onload = function(evt) {
resolve({ body: evt.target.response, ok: evt.target.status >= 200 && evt.target.status < 300 });
};
xhr.send(data);
});
}, /**
* @example
* ```js
* Http.download('http://xxx.com/some_api', {
* type: 'arraybuffer',
* progress: (loaded, total)=>{
* console.log(loaded, total);
* }
* })```
*
*
* @param {String} url
* @param {Object} opt
*/
download(url, opt) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = opt.type || ''; xhr.onprogress = opt.progress;
xhr.onerror = reject;
xhr.timeout = reject;
xhr.onload = function(evt) {
resolve({ body: evt.target.response, ok: evt.target.status >= 200 && evt.target.status < 300 });
};
xhr.send(null);
});
}
}; export default Http;
上一篇:layout内容整理


下一篇:oracle查询列合并为行(listagg简单用法)