拦截器(interceptors)通常用于发起 http 请求以前或以后对请求进行统一的处理,
如 token 实现的登陆鉴权(每一个请求带上 token),统一处理 404 响应等等。javascript
区别于 axios,fetch 没有搜到请求返回拦截器相关 api,那以前是怎么实现统一拦截的呢,
参照 antd-pro,写一个统一的请求方法,全部的请求都调用这个方法,从而实现请求与返回的拦截。
这样咱们每次都要去引入这个方法使用,那么有没有更好实现呢?vue
vue 双向绑定的原理java
极简的双向绑定ios
const obj = {}; Object.defineProperty(obj, 'text', { get: function() { console.log('get val');  }, set: function(newVal) { console.log('set val:' + newVal); document.getElementById('input').value = newVal; document.getElementById('span').innerHTML = newVal; } }); const input = document.getElementById('input'); input.addEventListener('keyup', function(e){ obj.text = e.target.value; })
其中咱们能够看到运用了看数据劫持。git
查看 MDN
咱们能够发现 defineProperty 的使用方法github
Object.defineProperty(obj, prop, descriptor);
descriptor 属性与方法包含
回想下咱们使用 fetch 的时候都是直接使用,因此 fetch 是 window 或者 global 对象下的一个属性啊,
每次咱们使用 fetch 的时候至关于访问了 window 或者 global 的属性,也就是上面的 get 方法
const originFetch = fetch; Object.defineProperty(window, "fetch", { configurable: true, enumerable: true, // writable: true, get() { return (url,options) => { return originFetch(url,{...options,...{ headers: { 'Content-Type': 'application/json;charset=UTF-8', Accept: 'application/json', token:localStorage.getItem('token') //这里统一加token 实现请求拦截 },...options.headers }}).then(checkStatus) // checkStatus 这里能够作返回错误处理,实现返回拦截 .then(response =>response.json()) } });
只要将上述代码贴到程序入口文件便可面试
此文是基于 defineProperty , Proxy 一样能够实现。
另外在小程序里面 request 方法是挂在 wx 下面,一样是能够实现,
具体实现 wx.requestjson