fetch拦截代理

前言

传统 Ajax 指的是 XMLHttpRequest(XHR),后续逐渐会被 Fetch 替代。

对于 IE8+ 以上浏览器,在生产环境使用 Fetch 是可行的;

由于 Fetch API 是基于 Promise 设计,有必要先学习一下 Promise,推荐阅读 MDN Promise 教程。旧浏览器不支持 Promise,需要使用 polyfill es6-promise

XMLHttpRequest 是一个设计粗糙的 API,不符合关注分离(Separation of Concerns)的原则,配置和调用方式非常混乱,而且基于事件的异步模型写起来也没有现代的 Promise,generator/yield,async/await 友好。

iOS fetch

业内目前有不少APP在iOS端使用WKwebview;

WKWebView会忽视默认的网络存储, NSURLCache, NSHTTPCookieStorage, NSCredentialStorage。 目前是这样的,WKWebView有自己的进程,同样也有自己的存储空间用来存储cookie和cache, 其他的网络类如NSURLConnection是无法访问到的。 同时WKWebView发起的资源请求也是不经过NSURLProtocol的,导致无法自定义请求。

WKWebView 请求携带的 Cookie 的 Secure 属性不齐全在后面拼接完整 Cookie 的 Secure 属性 cookie、 path、domain

Document.cookie - Web APIs | MDN

请求时携带的Cookie丢失或Cookie不相同,这就导致服务端请求异常,这时就需要针对APP做一个统一处理。

fetch拦截处理

前端拦截所有fetch请求,统一处理

//拦截原始的fetch方法
var oldFetchfn = fetch; 
//iOS WKwebview判断
if(oldFetchfn && window.webkit && window.webkit.messageHandlers){
    var current = new Date().getTime();
    current = parseInt((current / 1000) % 100000);
    var messageId = current+1;
    var globalId = null;    
    //定义新的fetch方法,封装原有的fetch方法
    //可定义成widow方法全局覆盖 也可export输出新的fetch模块这是就需要业务方使用新的fetch请求
    window.fetch = function(input, opts){
        //处理多个并发请求 每个请求回调赋值id
        globalId = messageId;
        messageId++;
        var message = {};
        message.id = globalId;
        message.data = opts.body;
        message.method = opts.method;
        message.url = input;
        message.headers = opts.headers;
        //判断iOS端cookie是否丢失 判断依据根据自己业务使用的关键cookie判断,
        //下面的判断是我本人业务开发时的关键cookie
        if(document.cookie.indexOf('PPU=') == -1 
        || document.cookie.indexOf('sign=') == -1
        || document.cookie.indexOf('source=') == -1){
            return new Promise((resolve, reject)=>{
                //此处是根据自己APP业务处理的 仅供参考
                var callback = "fetch_callback" + globalId
                window[callback] = function(id, native){
                    //native端完成网络请求返回response结果 resolve给业务调用方
                    if(globalId = id && native){
                        resolve(JSON.parse(native.data))
                    }
                    globalId = null;
                }
                //此处调用native端request网络请求
                WEBAPP.ajax(message.url, message.data, message.method, 
                    callback, message.headers, message.id);
            })
        }else{
            //此处是正常的原生fetch请求 添加超时处理
            return new Promise((resolve, reject)=>{
                var timeout = opts.timeout;
                if(timeout){
                    setTimeout(()=>{
                        reject(new Error("fetch timeout"));
                    },timeout)
                }
                oldFetchfn(input, opts)
                .then(res=>{
                    return res.json();
                })
                .then(
                    (res)=>{
                        resolve(res)
                    },
                    (err)=>{
                        reject(err)
                    }
                )
            })
        }
    }
}

前端正常使用fetch请求

fetch(url, {
    method: "GET",
    headers: {
        "Content-Type": "application/json"
    },
    credentials: "include"
})
    .then(res => {
        if (res && res.respCode == "0") {
            this.setState({ data: res.respData });
        } else {
            console.log("服务端异常")
        }
    })
    .catch(err => {
        console.log(err);
    });

   转载规则


《fetch拦截代理》 浅夏晴空 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录