攔截器(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