業務要求:
需要進入頁面時就要游客登陸拿到token;
之后的接口都是需要這個token;
其他操作則需要授權登陸,此時的token已失效;
token過久之后會過期;
業務實現:
1.全局攔截
fly.interceptors.request.use(request => {
const token = storage.get('jwt')
// 給所有請求添加自定義header
if (!jwt) {
fly.lock() // 進入接口后沒有token的需要鎖住請求
return store.dispatch('visitorLoginFun').then(res => { // 這里需要一個新的攔截器
if (res) {
const token = storage.get('token')
request.headers['Authorization'] = 'Bearer ' + token // 為隊列里的接口加token
return request
}
}).finally(() => {
fly.unlock()
})
} else {
request.headers['Accept'] =
'application/json,text/html;q=0.9,image/webp,*/*;q=0.8'
request.headers['Content-Type'] = 'application/json;charset=UTF-8'
request.headers['Authorization'] = 'Bearer ' + token
request.headers['client'] = client
request.headers['version'] = version
wx.showNavigationBarLoading()
return request
}
})
2.返回攔截
fly.interceptors.response.use(
(response, promise) => {
if (response.data.code === 1001) {
mpvue.navigateTo({url: '../accredit/main'}) // 返回提示需要登陸需要跳轉授權登陸頁 或者彈窗 授權只能通過按鈕觸發
}
if (response.data.code === 1002) {
fly.lock() //token過期 鎖住攔截器
return store.dispatch('accreditLogin').then(res => { // 使用新起的攔截器發送登陸接口
}).finally(() => fly.unlock()).then(() => {
return fly.request(response.request) // 返回上一個請求
})
}
return promise.resolve(obj)
}
}