Vue.js axios响应拦截获取返回状态码

axios响应拦截获取返回状态码方式整理

方法一

axios.interceptors.response.use(
	response => {
		console.log('拦截器响应成功')
		return response
	},
	error => {
		console.log('拦截器响应失败')
		console.log(error)
		if(error.request){
			console.log(error.request)
		} else if(error.response){
			console.log(error.response.data);
			console.log(error.response.status);
		}
		if (error && error.response) {
			switch (error.response.status) {
				case 400: error.message = '请求错误(400)'; 
					break;
				case 401: error.message = '未授权,请重新登录(401)';
					break;
				case 403: error.message = '拒绝访问(403)';
					break;
				case 404: error.message = '请求出错(404)'; 
					break;
				case 408: error.message = '请求超时(408)'; 
					break;
				case 500: error.message = '服务器错误(500)'; 
					break;
				case 501: error.message = '服务未实现(501)'; 
					break;
				case 502: error.message = '网络错误(502)'; 
					break;
				case 503: error.message = '服务不可用(503)'; 
					break;
				case 504: error.message = '网络超时(504)'; 
					break;
				case 505: error.message = 'HTTP版本不受支持(505)';
					break;
				default: error.message = '连接出错'(${error.response.status})!;
			}
		}else{
			error.message ='连接服务器失败!'
		}
		return Promise.reject(error)
	}
)

方法二

// request请求拦截器
axios.interceptors.request.use(
    config => {
        Indicator.open({
            text: '加载中...',
            spinnerType: 'fading-circle'
        });
         //如果cookie中存在Authorization
        if(sessionStorage.getItem('Authorization')){
            config.headers.common['Authorization'] = sessionStorage.getItem('Authorization')
            config.headers.common['loginAuth'] = sessionStorage.getItem('loginAuth')
        }
      return config
    },
    error => {
      Promise.reject(error)
    }
  );
  //response响应拦截器
axios.interceptors.response.use(
    response => {
      if(sessionStorage.getItem('Authorization')){
        // 返回code === 1 || 返回code === 2
        if(response.data.code === 1){
          MessageBox.alert(response.data.msg).then(action=>{})
        }else if(response.data.code === 2){
          MessageBox.alert(response.data.msg).then(action=>{
            sessionStorage.removeItem('Authorization')
            router.push('/login')
          })
        }
      }
        Indicator.close()  //响应成功,关闭全局的Indicator
        return response
    },
    error => {
        Indicator.close()  // 响应错误,关闭全局的Indicator
        if(error){
            const {response} = error
            if(response.status >= 400 && response.status < 500){
                MessageBox.alert('资源不存在,请稍后重试').then(action=>{
                })
            }else if(response.status >= 500){
                MessageBox.alert('服务异常,请稍后重试').then(action=>{
                })
            }
            if(response.data.message === 'Network Error'){
                MessageBox.alert('网络异常,请稍后重试').then(action=>{
                })
            }
        }
      return Promise.reject(error)
    }
);

方法三

// axios请求拦截器
// 每次发送axios请求,都要带上一个token
axios.defaults.timeout = 120000 // 设置默认timeout为2分钟
axios.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json; charset=UTF-8'
    config.headers['Cache-Control'] = 'no-catch'
    const token = window.localStorage.getItem('accesstoken')
    if (token) {
      config.headers.common['access-token'] = `${token}`
    }
    return config
  },
  err => {
    console.log(err)
    return Promise.reject(err)
  }
)
axios.interceptors.response.use(
  response => {
    const tokentimer = Number(window.localStorage.getItem('tokentimer'))
    const tokenTimerStamp = Number(response.headers['token-timestamp'])
    /* 时间戳比之前时间戳大的时候替换token */
    if (tokentimer < tokenTimerStamp) {
      window.localStorage.setItem('accesstoken', response.headers['access-token'])
      window.localStorage.setItem('tokentimer', response.headers['token-timestamp'])
    }
    if (response.status === 200) {
      // 导出成功不返回下面的字段
      let _isTrue = response.data.success // 返回成功
      let _message = response.data.message // 返回提示信息
      let codeNum = response.data.code
      let _code, _code3
      if (codeNum) {
        _code = codeNum.toString().slice(0, 1) // 返回失败
        _code3 = codeNum.toString().slice(0, 4)
      } else {
        // 排除导出时成功没有返回code  导致报错
        if (response.data.code) {
          Vue.prototype.$message({
            message: `${codeNum}请求异常,请联系管理员!`,
            type: 'error'
          })
        }
      }
      if (_isTrue && codeNum === 20000) { // 返回成功请求

      } else {
        if (_code === '2' && codeNum !== 20000) {
          Vue.prototype.$message({
            message: `${codeNum}:${_message}`,
            type: 'error'
          })
        } else if (_code === '5' || _code === '6') { // 状态码为5,6开头的为服务器错误
          Vue.prototype.$message({
            dangerouslyUseHTMLString: true,
            message: `${codeNum}:${_message}`,
            type: 'error'
          })
        } else if (_code === '4') { // 状态码为4开头的为权限问题,无法登录
          if (_code3 === '4032') {
            router.push('/login')
          } else {
            Vue.prototype.$message({
              message: `${codeNum}:${_message}`,
              type: 'error'
            })
          }
        }
      }
      return Promise.resolve(response)
    }
    return Promise.reject(response)
  },
  error => {
    if (error.response) {
      Vue.prototype.$message({
        message: '系统异常,请联系管理员!',
        type: 'error'
      })
    } else {
      Vue.prototype.$message({
        message: '网络不给力',
        type: 'error'
      })
    }
    return Promise.reject(error) // 返回接口返回的错误信息
  })

你可能感兴趣的:(Vue.js axios响应拦截获取返回状态码)