http-fetch-client介绍~

前言

之前在公司业务开发的时候经常会遇到这么几个问题:

  1. 如何统一处理各种500、400或者网络中断等问题
  2. 当前端页面越来复杂,基于安全性,当用户离开过久就会导致页面失效,就需要用户手动刷新页面。面对这种情况,是否可以通过设置ajax发送刷新请求,然后重发当前请求处理,避免用户手动刷新

在jQuery年代,我们可以通过ajaxSuccess等全局监听处理问题1(但是对重发,由于没有封装一层Request, 不能容易优雅的进行重发)。

在现在Fetch的时代,global handle已经不见,但是在你的业务开发中确需要你再次封装。

基于以上的情况,我开始考虑自己封装一个,给自己也给大家分享。

特点

http-fetch-client采用了中间件的形式创建回调函数。

example:

1
2
3
4
5
import FetchClient from 'http-fetch-client';
let fetch = new FetchClient();
fetch.get(...).use((response, request) => {
// 这里就是你的回调哦~~
})

应用场景

如果你需要一个全局的FetchClient对你所有的请求进行控制,解决问题1&问题2~

如何创建retry的特殊用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import FetchClient from 'http-fetch-client';
let fetch = new FetchClient();
let globalCount = 0;
let normalCount = 0;
fetch.use(function (response, request) {
// this 是 Handles 的实例
globalCount++;
if (response.text() !== 'success') {
// 创建一个新的FetchClient
let newFetchClient = new FetchClient();
// 重新绑定之前所有的回调函数
this.handleQueue.forEach((handle) => {
newFetchClient.use(handle);
});
newFetchClient.request(request);
return false;
}
});
fetch
.get('http://fake.com')
.use((response) => {
normalCount++;
console.log('response text', response.text());
console.log('normalCount', normalCount);
console.log('globalCount', globalCount);
})
// 如何请求第一次失败,返回不是success, 则重试一次,第二次才返回success
// console
// response text, success 成功拿到success
// normalCount, 1 业务回调只执行了1次
// globalCount, 2 全局重试执行了2次

Response

Method

  • text/json/blob
    对返回的内容进行格式化

    1
    2
    3
    4
    fetch.get(...).use((response) => {
    console.log(response.text()) // String: test
    console.log(response.json()) // Object: {a:'..'}
    })
  • getHeaders
    返回response headers

  • isTimeout 返回是否超时
  • isAborted 返回是否取消

Attribute

  • status {Number} http状态
  • ok {Boolean} http状态在200-300中间

Request

1
2
import { Request } from 'http-fetch-client';
new Request(url, options);

Method

  • getHeaders 获取请求头
  • setHeaders 设置请求头
  • getBody/getBodyForm/getBodyJson/getBodyFormData 获取请求body, 并转化为某种格式
  • setBody 设置请求body
  • getUrl/getUrlWithQuery(for GET) 获取url
  • getOptions 获取 options
  • setOptions 设置 options
  • getMethod 获取 method

Options Attribute

  • sendType {String} 发送的数据格式,支持 json/form(default),设置会会自动添加header中的 Content-Type

    1
    2
    3
    4
    {
    'json': 'application/json; charset=UTF-8', // default
    'form': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  • acceptType {String} 接受的数据格式,支持 json(default),设置会会自动添加header中的 Accept

    1
    2
    3
    {
    'json': 'application/json,text/javascript' // default
    }
  • async {Boolean}

  • body|data {Object}
  • headers {Object}

更多用法

参考:https://github.com/ignous/http-fetch-client

备注

项目地址:https://github.com/ignous/http-fetch-client

npm安装

1
npm install --save http-fetch-client