實現 fetch 請求返回的統一攔截

攔截器的目的

攔截器(interceptors)通常用於發起 http 請求以前或以後對請求進行統一的處理,
如 token 實現的登陸鑑權(每一個請求帶上 token),統一處理 404 響應等等。javascript

以前的實現

區別於 axios,fetch 沒有搜到請求返回攔截器相關 api,那以前是怎麼實現統一攔截的呢,
參照 antd-pro,寫一個統一的請求方法,全部的請求都調用這個方法,從而實現請求與返回的攔截。
這樣咱們每次都要去引入這個方法使用,那麼有沒有更好實現呢?vue

常見的一道面試題

vue 雙向綁定的原理java

  • vue2 基於 defineProperty
  • vue3 基於 Proxy

極簡的雙向綁定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

defineProperty

查看 MDN
咱們能夠發現 defineProperty 的使用方法github

Object.defineProperty(obj, prop, descriptor);
descriptor 屬性與方法包含
  • value
    屬性的值(不用多說了)
  • configurable: true,
    總開關,一旦爲 false,就不能再設置他的(value,writable,configurable)
  • enumerable: true,
    是否能在 for...in 循環中遍歷出來或在 Object.keys 中列舉出來。
  • writable: true,
    若是爲 false,屬性的值就不能被重寫,只能爲只讀了
  • set()
    設置屬性時候會調用
  • get()
    訪問屬性時候會調用
回想下咱們使用 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

  • 原文地址 fetch
  • 另外個人博客地址 blog會常常分享 最近的學習內容,項目中遇到的問題及解決方案
相關文章
相關標籤/搜索