javascript實現(xiàn)fetch請求返回的統(tǒng)一攔截
攔截器的目的
攔截器(interceptors)一般用于發(fā)起 http 請求之前或之后對請求進行統(tǒng)一的處理,
如 token 實現(xiàn)的登錄鑒權(quán)(每個請求帶上 token),統(tǒng)一處理 404 響應等等。
之前的實現(xiàn)
區(qū)別于 axios,fetch 沒有搜到請求返回攔截器相關(guān) api,那之前是怎么實現(xiàn)統(tǒng)一攔截的呢,
參照 antd-pro,寫一個統(tǒng)一的請求方法,所有的請求都調(diào)用這個方法,從而實現(xiàn)請求與返回的攔截。
這樣我們每次都要去引入這個方法使用,那么有沒有更好實現(xiàn)呢?
常見的一道面試題
vue 雙向綁定的原理
- vue2 基于 defineProperty
- vue3 基于 Proxy
極簡的雙向綁定
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; })
其中我們可以看到運用了看數(shù)據(jù)劫持。
defineProperty
查看 MDN
我們可以發(fā)現(xiàn) defineProperty 的使用方法
Object.defineProperty(obj, prop, descriptor);
descriptor 屬性與方法包含
value
屬性的值(不用多說了)
configurable: true,
總開關(guān),一旦為 false,就不能再設置他的(value,writable,configurable)
enumerable: true,
是否能在 for...in 循環(huán)中遍歷出來或在 Object.keys 中列舉出來。
writable: true,
如果為 false,屬性的值就不能被重寫,只能為只讀了
set()
設置屬性時候會調(diào)用
get()
訪問屬性時候會調(diào)用
回想下我們使用 fetch 的時候都是直接使用,所以 fetch 是 window 或者 global 對象下的一個屬性啊,
每次我們使用 fetch 的時候相當于訪問了 window 或者 global 的屬性,也就是上面的 get 方法
攔截器的實現(xiàn)
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') //這里統(tǒng)一加token 實現(xiàn)請求攔截 },...options.headers }}).then(checkStatus) // checkStatus 這里可以做返回錯誤處理,實現(xiàn)返回攔截 .then(response =>response.json()) } });
只要將上述代碼貼到程序入口文件即可
擴展
此文是基于 defineProperty , Proxy 同樣可以實現(xiàn)。
另外在小程序里面 request 方法是掛在 wx 下面,同樣是可以實現(xiàn),
具體實現(xiàn) wx.request
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
javascript通過獲取html標簽屬性class實現(xiàn)多選項卡的方法
這篇文章主要介紹了javascript通過獲取html標簽屬性class實現(xiàn)多選項卡的方法,涉及javascript針對頁面元素屬性與事件的相關(guān)操作技巧,需要的朋友可以參考下2015-07-07兩個JavaScript jsFiddle JSBin在線調(diào)試器
這兩個工具都是剛誕生不久,都還在不斷完善中,雖然目前jsFiddle要優(yōu)于JS Bin,但是我還是更看好后者2010-03-03vue?element?loading遮罩層添加按鈕功能實現(xiàn)
這篇文章主要介紹了vue?element?loading遮罩層添加按鈕功能實現(xiàn),通過實例代碼補充介紹了vue+elementui的this.$loading遮罩使用方法,需要的朋友可以參考下2024-03-03