vue中用axios拦截器拦截请求和响应

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复制代码


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值