vue 请求拦截 接口报错 自动跳转到503提示页面

做项目的时候,有时候接口报错,或者服务器挂了,我们需要做一个错误页面,告诉用户此时服务器挂了。在网上找了一下,并没有清晰易懂的文档,我就把我的项目里面用到的分享出来。

新建一个请求拦截js文件,代码如下:

import axios from 'axios'
import router from '../router.js'

// 创建 axios 实例
export const Axios = axios.create({
  timeout: 15000
})

window.cancelInterface = []
//POST传参序列化(添加请求拦截器)
// 在发送请求之前做某件事
axios.interceptors.request.use(
  config => {
    config.cancelToken = new axios.CancelToken(cancel => {
      if (!window.cancelInterface) {
        window.cancelInterface = []
      }
      window.cancelInterface.push({
        cancel
      })
    })
    // console.log('config.token', config)
    if (config.token != 'none') {
      if (localStorage.token) {
        config.headers.Authorization = 'Bearer ' + localStorage.token
      }
    }

    return config
  },
  error => { 
    return Promise.reject(error)
  }
)

//返回状态判断(添加响应拦截器)
axios.defaults.headers['Content-Type'] = 'application/json; charset=UTF-8'
axios.interceptors.response.use(
  res => {
    if (res.data.code == '401') {
      router.push({
        path: '/login',
        query: {
          redirect: location.hostname
        }
      })
      return
    }
    //503跳转到错误页
    if (res.data.code == '503') {
      router.push({
        path: '/error',
        query: {
          redirect: location.hostname
        }
      })
      return
    }
    return res
  },
  error => {
    if (error.response.status === 401 || error.response.status === 403) {
      router.push({
        path: '/login',
        query: {
          redirect: location.hostname
        }
      })
    } else if (error.response.status === 503 ) {
      router.push({
        path: '/error',
        query: {
          redirect: location.hostname
        }
      })
    } else if (error.response.status === 500) {
      // 服务器错误
      return Promise.reject(error.response.data)
    } 
    // 返回 response 里的错误信息
    return Promise.reject(error.response.data)
  }
)
// 将 Axios 实例添加到Vue的原型对象上
export default {
  install(Vue) {
    Object.defineProperty(Vue.prototype, '$http', {
      value: Axios
    })
  }
}

如此,大功告成

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值