vue中用axios攔截器攔截請求和響應

YYX發表於2018-02-28

import axios from 'axios'引入模組

var api = axios.create({
  baseURL: ENV,
  timeout: 5000,
  headers: {'Content-Type': 'application/json'}
})
// request請求配置
api.interceptors.request.use(config => {
  config.headers['system'] = apiconfig.SYSTEM
  if (sessionStorage) {
    const token = sessionStorage.getItem(apiconfig.TOKEN_KEY)
    if (token) {
      config.headers['Authorization'] = 'bearer ' + token // 讓每個請求攜帶token--['X-Token']為自定義key 請根據實際情況自行修改
    }
    return config
  } else {
    Notification({
      title: '錯誤',
      message: '您的瀏覽器版本太低,請升級瀏覽器',
      type: 'error'
    })
  }}, error => {
  console.error(error)
  Notification({
    title: '錯誤',
    message: '請求失敗:' + error.message,
    type: 'error'
  })
  Promise.reject(error)
})
// respone攔截器
api.interceptors.response.use(
  response => {
    return response
  },  error => {
    let errorMsg = ''
    if (error.toString().indexOf('timeout') !== -1) {
      errorMsg = '連線伺服器超時'
    } else {
      const errorStatus = error.response.status
      const resErrorMsg = errorStatus + ':' + error.response.data.message
      switch (errorStatus) {
        case 401:
          router.push('/login')
          window.sessionStorage.removeItem(apiconfig.TOKEN_KEY)
          window.sessionStorage.removeItem(APP_TABVIEWLIST_KEY)
          store.commit('SET_TAB_VIEW_LIST', [])
          // console.log('match', router.currentRoute)
          Notification({
            title: '請重新登入',
            message: '登入已過期,請重新登入',
            showIcon: true,
            center: true,
            type: 'error'
          })
          return
        case 403:
          errorMsg = '沒有許可權'
          break
        case 404:
          errorMsg = '請求路徑找不到'
          break
        case 422:
          errorMsg = resErrorMsg + ':' + JSON.stringify(error.response.data.data)
          break
        default:
          // console.log('.api..baseURL.......', resErrorMsg)
          errorMsg = resErrorMsg
      }
    }
    Notification({
      title: '錯誤',
      message: errorMsg,
      dangerouslyUseHTMLString: true,
      type: 'error',
      customClass: 'tolos-msg'
    })
    return Promise.reject(error)
  })
export default api複製程式碼


相關文章