H5W3
当前位置:H5W3 > 其他技术问题 > 正文

vue.js怎么处理无网状态下,接口请求报错

  1. vue项目中,用axios统一封装了请求接口,使用了拦截器处理响应数据
// http response 拦截器
axios.interceptors.response.use(response => {
  // 系统报错
  if (response.data && response.data.err !== 0) {
    router.push({name: 'err', query: {code: response.data.err}});
  }

  return response
}, error => {
  console.log('++++++++++++++++++++++++++', error)
  if (error.response.status === 404) {
    router.push({name: 'err', query: {code: error.response.status}})
  }

  if (error.response.status === 401) {
    router.push({name: 'err', query: {code: error.response.status}});
  }

  if (error.response.status === 500) {
    router.push({name: 'err', query: {code: error.response.status}});
  }

  return Promise.resolve(error.response)
})

打包后,部署在测试环境中,断开网络后报错
图片描述

请问,怎么获取断网下状态,给出提示信息

回答:

axios.interceptors.response.use(response => {
  // 系统报错
  if (response.data && response.data.err !== 0) {
    router.push({name: 'err', query: {code: response.data.err}});
  }

  return response
}, error => {
  if (!error.response) {
    // 断网了  
  }
  console.log('++++++++++++++++++++++++++', error)
  if (error.response.status === 404) {
    router.push({name: 'err', query: {code: error.response.status}})
  }

  if (error.response.status === 401) {
    router.push({name: 'err', query: {code: error.response.status}});
  }

  if (error.response.status === 500) {
    router.push({name: 'err', query: {code: error.response.status}});
  }

  return Promise.resolve(error.response)
})

每个if下面建议加return

本文地址:H5W3 » vue.js怎么处理无网状态下,接口请求报错

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址