請求攔截器 與 響應(yīng)攔截器(Vue)

前提:

請求攔截器和響應(yīng)攔截器主要應(yīng)用場景:請求網(wǎng)絡(luò)接口

  • 請求攔截器:發(fā)送請求的時候,攜帶一些信息
  • 響應(yīng)攔截器:接收到數(shù)據(jù)的時候,進(jìn)行數(shù)據(jù)過濾、對狀態(tài)碼判斷,進(jìn)行對應(yīng)的操作

Vue的網(wǎng)絡(luò)請求可以在main.js里面進(jìn)行封裝配置

import axios from 'axios'
// 為axios配置請求的根路徑
axios.defaults.baseURL = 'http://43.142.35.140:8890/api/private/v1/'
// 設(shè)置攔截器
axios.interceptors.request.use(config => {
  // 為請求頭對象,添加Token驗證的Authorization字段,才可以調(diào)用有權(quán)限的API
  config.headers.Authorization = window.sessionStorage.getItem('token')
  // 在最后必須return config
  return config
})
// 把a(bǔ)xios包掛載到vue的原型對象上
Vue.prototype.$http = axios

一、請求攔截器

  • 請求攔截器的作用是在請求發(fā)送前進(jìn)行一些操作,例如在每個請求體里加上token,統(tǒng)一做了處理如果以后要改也非常容易。

代碼實現(xiàn)(Vue)

// 請求超時時間
axios.defaults.timeout = 120000

// 添加請求攔截器
axios.interceptors.request.use(
  config => {
    // 在發(fā)送請求之前做些什么
    // 判斷是否存在token,如果存在將每個頁面header都添加token
    if (window.sessionStorage.getItem('DT')) {
      // 請求頭配置全局token
      config.headers.DT = window.sessionStorage.getItem('DT')
    }
    return config
  },
  err => {
    // 對請求錯誤做些什么
    Vue.prototype.$message.error('請求超時')
    return Promise.reject(err)
  }
)

二、響應(yīng)攔截器

  • 響應(yīng)攔截器的作用是在接收到響應(yīng)后進(jìn)行一些操作
    • 例如在服務(wù)器返回登錄狀態(tài)失效,需要重新登錄的時候,跳轉(zhuǎn)到登錄頁。
    • 對接收到的數(shù)據(jù)進(jìn)行處理篩選,只留下需要的數(shù)據(jù)
  • 響應(yīng)攔截器也是一樣如此,就是在請求結(jié)果返回后,先不直接導(dǎo)出,而是先對響應(yīng)碼等等進(jìn)行處理,處理好后再導(dǎo)出給頁面,如果將這個對響應(yīng)碼的處理過程抽出來,就成了所謂的響應(yīng)攔截器。

代碼實現(xiàn)(Vue)

// 響應(yīng)攔截器
axios.interceptors.response.use(
  response => {
    // res是響應(yīng)的結(jié)果
    switch (response.data.code) {
      case 401:
        // 登錄失效
        // 響應(yīng)成功的攔截
        console.log('響應(yīng)攔截器:')
        // console.log(response.data)
        Vue.prototype.$message.error(response.data.message)
        sessionStorage.removeItem('DT')
        router.push('/login')
        break
      case 404:
        if (response.data.message !== null) {
          Vue.prototype.$message.error(response.data.message)
        } else {
          Vue.prototype.$message.error('未知錯誤')
        }
        break
      case 500:
        // 錯誤
        if (response.data.message !== null) {
          Vue.prototype.$message.error(response.data.message)
        } else {
          Vue.prototype.$message.error('未知錯誤')
        }
        break
      default:
        return response
    }
    return response
  },
  err => {
    if (err.response.data.message) {
      Vue.prototype.$message.error(err.response.data.message)
      return Promise.reject(err.response.data.message) // 返回接口返回的錯誤信息
    } else {
      // 返回狀態(tài)碼不為200時候的錯誤處理
      Vue.prototype.$message.error(err.toString())
      return Promise.resolve(err)
    }
  }
)

三、頁面中請求接口時

// 用戶登錄提交
    login() {
      // debugger
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        if (valid) {const userInfo = {
            username: this.loginForm.username,
            password: this.loginForm.password
          }
          // 登錄之前去除token
          window.sessionStorage.removeItem('DT')
          const { data: res } = await this.$http.post('/system/login', userInfo)
          if (res.code !== 200) {
            this.initCaptcha()
            return
          }
          this.$message.success('登錄成功')
          window.sessionStorage.setItem('DT', res.result.token)
          this.$router.push('/main')
        }
      })
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容