使用inteceptor
攔截器可以在請求發送前和發送請求後做一些處理。
基本用法
Vue.http.interceptors.push((request, next) => {
// ...
// 請求發送前的處理邏輯
// ...next((response) => {
// ...
// 請求發送後的處理邏輯
// ...
// 根據請求的狀態,response參數會返回給successCallback或errorCallbackreturn response
})
})
main.js代碼段如下:
Vue.http.interceptors.push((request, next) => {
request.headers.Authorization = 'Bearer ' + window.localStorage.getItem('jwt_token')
next((response) => {
if (response.status === 401) {
var eid = 1
window.location.href = http://auth.demo.ecfex.org/?appId=${appId}&eid=${eid}
}
})
})
錯誤現象:
頁面地址會自動添加關於jwt_token的相關信息,假如在這裏加載頁面前有讀取操作並且刷新頁面,則頁面會不斷刷新http://1.ctts.local.ecfex.org:8080/auth?jwt_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlaWQiOiIxIiwidXNlcmlkIjoicGVuZ3poZW5zaGVuZyIsImlhdCI6MTQ2OTQzNjcwNn0.MwjY-Kl3R1YiM9xx5bTsj-YzC8Mk5lpE_O0LzbTCMps
錯誤原因:
request.headers.Authorization = 'Bearer ' + window.localStorage.getItem('jwt_token')
這條語句中的 'Bearer ' 不是 'Bearer' ,請注意末尾是有空格符的!!!