taue997

umi-request:

网络请求库,基于fetch封装,兼具fetch 和 axios 的所有特点,具有缓存,超时,字符编码处理,错误处理等常用功能。

1 支持url 参数自动序列化。

2 post 数据提交方式简化。

3 api超时支持。

4 api请求缓存支持。

5 支持处理gbk.(gbk 一种字符集)。

6 类axios的request和response拦截器(interceptors)支持。

7 统一的错误处理方式。

8 类koa洋葱机制的use中间件机制支持。

9 类axios的取消处理。(cancel Token).

10 支持Node环境发送http请求。

相较于fetch和axios 而言具有更多的功能,支持取消请求,中间件,超时 ,缓存等功能。

上手的基本示例:

首先,执行get 请求:

 1 import request from \'umi-request\';
 2 
 3 request
 4   .get(\'/api/v1/xxx?id=1\')
 5   .then(function(response) {
 6     console.log(response);
 7   })
 8   .catch(function(error) {
 9     console.log(error);
10   });

同时,也可将请求的url参数放在options,params中:

 1 request.get(\'/api/v1/xxx\', {
 2     params: {
 3       id: 1,
 4     },
 5   })
 6   .then(function(response) {
 7     console.log(response);
 8   })
 9   .catch(function(error) {
10     console.log(error);
11   });

执行基本的post请求:

 1 request
 2   .post(\'/api/v1/user\', {
 3     data: {
 4       name: \'Mike\',
 5     },
 6   })
 7   .then(function(response) {
 8     console.log(response);
 9   })
10   .catch(function(error) {
11     console.log(error);
12   });

umi-request的相关API:

可以通过向 umi-request 传参来发起请求,在method中指定请求方式。

umi-request(url[, options]):

示例:

 1 import request from \'umi-request\';
 2 
 3 request(\'/api/v1/xxx\', {
 4   method: \'get\',
 5   params: { id: 1 },
 6 })
 7   .then(function(response) {
 8     console.log(response);
 9   })
10   .catch(function(error) {
11     console.log(error);
12   });
13 
14 request(\'/api/v1/user\', {
15   method: \'post\',
16   data: {
17     name: \'Mike\',
18   },
19 })
20   .then(function(response) {
21     console.log(response);
22   })
23   .catch(function(error) {
24     console.log(error);
25   });

相关请求方法的别名,之后可以不用单独在method中配置请求方式。

request.get(url[, options])

request.post(url[, options])

request.delete(url[, options])

request.put(url[, options])

request.patch(url[, options])

request.head(url[, options])

request.options(url[, options])

如果有些配置多个请求当中都有使用到,则可以通过extend创建一个umi-request实例,将公共的配置放置在实例中。则可以实现配置的简化:extend([options])

示例:

1 import { extend } from \'umi-request\';
2 
3 const request = extend({
4   prefix: \'/api/v1\',
5   timeout: 1000,
6   headers: {
7     \'Content-Type\': \'multipart/form-data\',
8   },
9 });

之后这个get请求便可以使用extend中的公共配置。

1 request
2   .get(\'/user\')
3   .then(function(response) {
4     console.log(response);
5   })
6   .catch(function(error) {
7     console.log(error);
8   });

其他的请求方式同理。例如:post delete put patch head options 等。

请求参数的配置:request options 中的参数详情:

 

 

 

 

 extend options的参数支持以上的所有参数。

 参数含义详情:

  1 {
  2   // \'method\' 是创建请求时使用的方法
  3   method: \'get\', // default
  4 
  5   // \'params\' 是即将于请求一起发送的 URL 参数,参数会自动 encode 后添加到 URL 中
  6   // 类型需为 Object 对象或者 URLSearchParams 对象
  7   params: { id: 1 },
  8 
  9   // \'paramsSerializer\' 开发者可通过该函数对 params 做序列化(注意:此时传入的 params 为合并了 extends 中 params 参数的对象,如果传入的是 URLSearchParams 对象会转化为 Object 对象
 10   paramsSerializer: function (params) {
 11     return Qs.stringify(params, { arrayFormat: \'brackets\' })
 12   },
 13 
 14   // \'data\' 作为请求主体被发送的数据
 15   // 适用于这些请求方法 \'PUT\', \'POST\', 和 \'PATCH\'
 16   // 必须是以下类型之一:
 17   // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
 18   // - 浏览器专属:FormData, File, Blob
 19   // - Node 专属: Stream
 20   data: { name: \'Mike\' },
 21 
 22   // \'headers\' 请求头
 23   headers: { \'Content-Type\': \'multipart/form-data\' },
 24 
 25   // \'timeout\' 指定请求超时的毫秒数(0 表示无超时时间)
 26   // 如果请求超过了 \'timeout\' 时间,请求将被中断并抛出请求异常
 27   timeout: 1000,
 28 
 29   // ’prefix‘ 前缀,统一设置 url 前缀
 30   // ( e.g. request(\'/user/save\', { prefix: \'/api/v1\' }) => request(\'/api/v1/user/save\') )
 31   prefix: \'\',
 32 
 33   // ’suffix‘ 后缀,统一设置 url 后缀
 34   // ( e.g. request(\'/api/v1/user/save\', { suffix: \'.json\'}) => request(\'/api/v1/user/save.json\') )
 35   suffix: \'\',
 36 
 37   // \'credentials\' 发送带凭据的请求
 38   // 为了让浏览器发送包含凭据的请求(即使是跨域源),需要设置 credentials: \'include\'
 39   // 如果只想在请求URL与调用脚本位于同一起源处时发送凭据,请添加credentials: \'same-origin\'
 40   // 要改为确保浏览器不在请求中包含凭据,请使用credentials: \'omit\'
 41   credentials: \'same-origin\', // default
 42 
 43   // ’useCache‘ 是否使用缓存,当值为 true 时,GET 请求在 ttl 毫秒内将被缓存,缓存策略唯一 key 为 url + params + method 组合
 44   useCache: false, // default
 45 
 46   // ’ttl‘ 缓存时长(毫秒), 0 为不过期
 47   ttl: 60000,
 48 
 49   // \'maxCache\' 最大缓存数, 0 为无限制
 50   maxCache: 0,
 51 
 52   // 根据协议规范, GET 请求用于获取、查询服务端数据,在数据更新频率不频繁的情况下做必要的缓存能减少服务端的压力,因为缓存策略是默认对 GET 请求做缓存,但对于一些特殊场景需要缓存其他类型请求的响应数据时,我们提供 validateCache 供用户自定义何时需要进行缓存, key 依旧为 url + params + method
 53   validateCache: (url, options) => { return options.method.toLowerCase() === \'get\' },
 54 
 55   // \'requestType\' 当 data 为对象或者数组时, umi-request 会根据 requestType 动态添加 headers 和设置 body(可传入 headers 覆盖 Accept 和 Content-Type 头部属性):
 56   // 1. requestType === \'json\' 时, (默认为 json )
 57   // options.headers = {
 58   //   Accept: \'application/json\',
 59   //   \'Content-Type\': \'application/json;charset=UTF-8\',
 60   //   ...options.headers,
 61   // }
 62   // options.body = JSON.stringify(data)
 63   // 2. requestType === \'form\' 时,
 64   // options.headers = {
 65   //   Accept: \'application/json\',
 66   //   \'Content-Type\': \'application/x-www-form-urlencoded;charset=UTF-8\',
 67   //   ...options.headers,
 68   // };
 69   // options.body = query-string.stringify(data);
 70   // 3. 其他 requestType
 71   // options.headers = {
 72   //   Accept: \'application/json\',
 73   //   ...options.headers,
 74   // };
 75   // options.body = data;
 76   requestType: \'json\', // default
 77 
 78   // ’parseResponse‘ 是否对请求返回的 Response 对象做格式、状态码解析
 79   parseResponse: true, // default
 80 
 81   // ’charset‘ 当服务端返回的数据编码类型为 gbk 时可使用该参数,umi-request 会按 gbk 编码做解析,避免得到乱码, 默认为 utf8
 82   // 当 parseResponse 值为 false 时该参数无效
 83   charset: \'gbk\',
 84 
 85   // \'responseType\': 如何解析返回的数据,当 parseResponse 值为 false 时该参数无效
 86   // 默认为 \'json\', 对返回结果进行 Response.text().then( d => JSON.parse(d) ) 解析
 87   // 其他(text, blob, arrayBuffer, formData), 做 Response[responseType]() 解析
 88   responseType: \'json\', // default
 89 
 90   // \'throwErrIfParseFail\': 当 responseType 为 json 但 JSON.parse(data) fail 时,是否抛出异常。默认不抛出异常而返回 Response.text() 后的结果,如需要抛出异常,可设置 throwErrIfParseFail 为 true
 91   throwErrIfParseFail: false, // default
 92 
 93   // \'getResponse\': 是否获取源 Response, 返回结果将包含一层: { data, response }
 94   getResponse: false,// default
 95 
 96   // \'errorHandler\' 统一的异常处理,供开发者对请求发生的异常做统一处理,详细使用请参考下方的错误处理文档
 97   errorHandler: function(error) { /* 异常处理 */ },
 98 
 99   // \'cancelToken\' 取消请求的 Token,详细使用请参考下方取消请求文档
100   cancelToken: null,
101 }

实例化请求实例之后,若还需要动态更新参数,umi-request中的extendOptions方法供用户进行更新。

const request = extend({ timeout: 1000, params: { a: \'1\' } });
// 默认参数是 { timeout: 1000, params: { a: \'1\' }}

request.extendOptions({ timeout: 3000, params: { b: \'2\' } });
// 此时默认参数是 { timeout: 3000, params: { a: \'1\', b: \'2\' }}

响应结构:

响应对象Response如下:

 1 {
 2   // `data` 由服务器提供的响应, 需要进行解析才能获取
 3   data: {},
 4 
 5   // `status` 来自服务器响应的 HTTP 状态码
 6   status: 200,
 7 
 8   // `statusText` 来自服务器响应的 HTTP 状态信息
 9   statusText: \'OK\',
10 
11   // `headers` 服务器响应的头
12   headers: {},
13 }

当 options.getResponse === false 时, 响应结构为解析后的 data:

request.get(\'/api/v1/xxx\', { getResponse: false }).then(function(data) {
  console.log(data);
});

当 options.getResponse === true 时,响应结构为包含 data 和 Response 的对象:

request.get(\'/api/v1/xxx\', { getResponse: true }).then(function({ data, response }) {
  console.log(data);
  console.log(response.status);
  console.log(response.statusText);
  console.log(response.headers);
});

错误处理:

 1 import request, { extend } from \'umi-request\';
 2 
 3 const errorHandler = function(error) {
 4   const codeMap = {
 5     \'021\': \'发生错误啦\',
 6     \'022\': \'发生大大大大错误啦\',
 7     // ....
 8   };
 9   if (error.response) {
10     // 请求已发送但服务端返回状态码非 2xx 的响应
11     console.log(error.response.status);
12     console.log(error.response.headers);
13     console.log(error.data);
14     console.log(error.request);
15     console.log(codeMap[error.data.status]);
16   } else {
17     // 请求初始化时出错或者没有响应返回的异常
18     console.log(error.message);
19   }
20 
21   throw error; // 如果throw. 错误将继续抛出.
22 
23   // 如果return, 则将值作为返回. \'return;\' 相当于return undefined, 在处理结果时判断response是否有值即可.
24   // return {some: \'data\'};
25 };
26 
27 // 1. 作为统一错误处理
28 const extendRequest = extend({ errorHandler });
29 
30 // 2. 单独特殊处理, 如果配置了统一处理, 但某个api需要特殊处理. 则在请求时, 将errorHandler作为参数传入.
31 request(\'/api/v1/xxx\', { errorHandler });
32 
33 // 3. 通过 Promise.catch 做错误处理
34 request(\'/api/v1/xxx\')
35   .then(function(response) {
36     console.log(response);
37   })
38   .catch(function(error) {
39     return errorHandler(error);
40   });

中间件机制,详情请转至:https://github.com/umijs/umi-request/blob/master/README_zh-CN.md

 

 

 

 

分类:

技术点:

相关文章: