1.0.10 • Published 1 year ago

xhr-easy v1.0.10

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

easy-fetch

免责声明

本库遵循ISC协议。且只是对浏览器或类浏览器原生能力的简单封装。因此因为使用本库所产生的任何损失或用于违规用图所产生的法律风险等,本人概不负责。继续使用表示您知晓并同意该条款。否则请立即删除。

目标

本库是对fetch、XMLHttpRequest的简单基础封装。目的是封装一个具备完整功能,在项目中在可以再次封装的轻量级请求库。

起因

封装该库的初衷是因为市面上的库要么比较老旧,基于XMLHttpRequest封装。要么使用方式复杂需要单独学习。要么功能不全。
为了自己使用方便,无奈选择自行封装。
完全按fetch API规范封装。返回Promise,传参为url + options格式。
支持自定义:请求方法、请求头、请求体、超时时间、手动取消、返回进度等。

关于返回值格式:

在服务端(Server)正确响应的情况:格式为json时自动解析为对象,否则:直接为服务端返回原始格式字符串,可自行解析。
在客户端(Client)错误的返回格式:{code: 1001, msg: '错误说明'}。
  • 1、本库不在乎Server返回格式,但推荐Server返回格(下文简称:推荐格式)式为 code: 状态代码Number,msg:错误/成功消息String,data:正常数据any
  • 2、无论返回哪种格式"都推荐每个具体项目"在返回Promise的基础上再次封装。因Client就用该格式返回错误,所以用!res.code判断(以下简称:判断)过滤非服务器返回的错误数据。
    • 2.1、"判断"为true(code字段不存在或为0),就是服务器返回,用return返回到外层Promise。为false,但又有数据需要到业务中,可以用||加判断条件。
    • 2.2、"判断"为false,用throw抛出错误,到catch中统一处理,如:Server、Client统一的错误提示。
  • 3、当Server使用"推荐格式",在多封装一次后,then里的就可以写纯业务逻辑了。
  • 4、当Server不使用"推荐格式",在多封装一次后,在then里可能还要再次判断服务器返回里的错误提示。如格式固定,也可上次封装过滤服务器返回错误,或再次封装。
所以对返回值只做了简单处理。因返回的是Promise, 所以可以很简单的再次封装。只要按Promise规范套多少层都可以。
可参考最下方:3个再次封装示例。

使用说明

  • 包含的所有方法:request、request.xhr、request.easy、request.toParams、request._toParams。
  • 其中 request、request.xhr、request.easy 传参方式、返回(Promise) 均为fetch API形式。
  • request 基于fetch封装的的网络请求。支持设置:请求方法(method)、请求头(headers)、请求体(body)、超时时间(timeout)、手动取消(cancel)、响应进度回调(onProgress)。
  • request.xhr 基于XMLHttpRequest封装的的网络请求。请求格式同request。另外多了:上传进度回调(upProgress)、请求失败重试次数(maxRetries)。
  • request.easy 基于XMLHttpRequest封装的的简单网络请求。只支持: 请求方法(method)、请求头(headers)、请求体(body)。完全原生,除了封装为fetch API形式外不做任何处理。
  • request.toParams 基于URLSearchParams的对象转key=value字符串。按key升序排列。用于GET请求的时候将body转为url后的参数字符串。
  • request._toParams 在不支持URLSearchParams时的替补。

安装:

npm install easy-fetch --save;

引入

import { requset } 'easy-fetch';
在不支持可选链运算符(?.)的环境引入:
import { requset } 'easy-fetch/dist/es5.js';

简单请求

request('https://example.com')
.then(……)
.catch(……);

get 请求。

body会按key升序排序后自动转为key=value形式拼接到url后面. 如:https://example.com?key=value&key=value

request('https://example.com', {method: 'GET', body: {……}})
.then(……)
.catch(……);

post 请求。

const options = {
  method: 'POST', // 请求方法
  body: {……}, // 请求体 可选
  headers: {……}, // 请求头 可选
  timeout: 60000, // 超时时间-毫秒 可选
  cancel: {……}, // 取消对象。可以用options.cancel.abort();手动取消 可选
  onProgress: (loaded, total)=>{……} // 返回进度,会在每个阶段调用该函数并传入loaded: 完成字节, total: 总字节。 可选
};
request('https://example.com', options).then(……).catch(……);

request.xhr使用方法同request。

options.maxRetries = 5; //  请求失败
options.upProgress = (loaded, total)=>{……}; // 上传进度,会在每个阶段调用该函数并传入loaded: 完成字节, total: 总字节。 可选
request.xhr('https://example.com', options).then(……).catch(……);

request.easy使用方法同request。

request.xhr('https://example.com', {method: 'POST', body: {……}, headers: {……}}).then(……).catch(……);

request.toParams对象转key=value形式字符串

const str = request.toParams({……})

request._toParams同request.toParams

const str = request.toParams({……})

再次封装示例:

请求拦截封装示例 实现在headers加入token

export const http = (url, options)=>{
  options.Authorization = sessionStorage.getItem('token');
  return request(url, options);
}

返回拦截封装示例 在then内用throw将服务端返回的错误定向到catch,then内只剩下正确反回值。服务端、客服端的错误都在catch中处理。

export const httpHandel = (method, body)=>{
  return http('https://example.com', {method, body}).then(res=>{
    // 假设服务端成功返回格式:{code: 0, data: [……]}
    // 假设服务端失败返回格式:{code: 1001, msg: '出错了'}
    if (!res.code || res.data){
      // 服务器返回:code为0/空 或有data字段的 用return返回到外层的then处理
      return res;
    }else{
      // 服务器返回:code不为0, 且没有data的 表示服务端返回的错误,可用throw重定向到catch里统一处理
      throw res;
    }
  }).catch(err=>{
    throw typeof err === 'object' && (err.code || err.msg) ? err : {code: -1, msg: err}; 
    // err是对象并且存在code或msg字段 就直接抛出错误。否则规范成统一的错误格式再抛出。便于次再外层的catch统一提示错误等。
  })
}

返回拦截封装示例 then和catch都反回外层处理。用finally关闭页面上的反馈动画

export const businessHttp = (method, body)=>{
  return httpHandel(method, body)
  .then(res=>res)
  .catch(err=> {
    throw err;
  })
  .finally(()=>{
    this.loading = false;
  });
}