axios攔截器設置
應用場景
請求攔截器用於在接口請求之前做的處理,比如爲每個請求帶上相應的參數(token,時間戳等)。
返回攔截器用於在接口返回之後做的處理,比如對返回的狀態進行判斷(token是否過期)。
攔截器的使用
1、在src目錄下建立api文件夾
2、文件夾內建立axios.js文件,進行接口請求的初始化配置
import axios from 'axios'
let instance = axios.create({
baseURL: "http://localhost:3000/",
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
//請求攔截器
instance.interceptors.request.use(config => { //攔截請求,做統一處理
const token = "asdasdk"
//在每個http header都加上token
config.headers.authorization = token
return config
}, err => {//失敗
return Promise.reject(err)
})
//響應攔截器
instance.interceptors.response.use(response => { //攔截響應,做統一處理
if (response.data.code) {
switch (response.data.code) {
case 200:
console.log("1111")
}
}
return response
}, err => { //無響應時的處理
return Promise.reject(err.response.status)
})
export default instance
3、在main.js中引入,並將其綁定到Vue原型上,設爲全局,不用在每個頁面重新引入
import instance from './api/axios'
Vue.prototype.$http = instance
4、頁面使用
this.$http.get(url).then(r => console.log(r)).catch(err => console.log(err))
this.$http.post(url, params).then(r => console.log(r)).catch(err => console.log(err))
5、效果展示
axios攔截器實現原理剖析
axios接口請求內部流程
axios原理簡化
function Axios(){
this.interceptors = {
//兩個攔截器
request: new interceptorsManner(),
response: new interceptorsManner()
}
}
//真正的請求
Axios.prototype.request = function(){
let chain = [dispatchRequest, undefined];//這兒的undefined是爲了補位,因爲攔截器的返回有兩個
let promise = Promise.resolve();
//將兩個攔截器中的回調加入到chain數組中
this.interceptors.request.handler.forEach((interceptor)=>{
chain.unshift(interceptor.fulfilled, interceptor.rejected);
})
this.interceptors.response.handler.forEach((interceptor)=>{
chain.push(interceptor.fulfilled, interceptor.rejected);
})
while(chain.length){
//promise.then的鏈式調用,下一個then中的chain爲上一個中的返回值,每次會減去兩個
//這樣就實現了在請求的時候,先去調用請求攔截器的內容,再去請求接口,返回之後再去執行響應攔截器的內容
promise = promise.then(chain.shift(),chain.shift());
}
}
function interceptorsManner(){
this.handler = [];
}
interceptorsManner.prototype.use = function(fulfilled,rejected){
//將成功與失敗的回調push到handler中
this.handler.push({
fulfilled: fulfilled,
rejected: rejected
})
}
//類似方法批量註冊,實現多種請求
util.forEach(["get","post","delete"],(methods)=>{
Axios.prototype[methods] = function(url,config){
return this.request(util.merge(config||{},{//合併
method: methods,
url: url
}))
}
})