当前位置:   article > 正文

axios拦截器_axios 拦截器 ts

axios 拦截器 ts

axios拦截器

实例化

const myAxios = axios.create({
    baseURL: 'http://url:port',
    timeOut: 100
})
  • 1
  • 2
  • 3
  • 4

请求拦截器

发送的请求会被拦截,进行处理后放行。

//设置请求拦截器
axios.interceptors.request.use(function (config) {
	//Do something before request is sent
	//比如Token就可以在这里添加
    return config
}, function (error) {
    //Do something with request error
    return Promise.reject(error)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

响应拦截器

服务器返回的结果会被拦截,进行预处理后放行。

//设置响应拦截器
axios.interceptors.response.use(function (response) {
	//Do something before request is sent
    return response
}, function (error) {
    //Do something with request error
    return Promise.reject(error)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

请求拦截器和响应拦截器的回调都必须return,否则将无法放行请求或者响应。

status报错拦截处理

Axios.interceptors.response.use(
  response => {
    return response
  },  
  err => {
    if (err.response) {
      console.log('响应式报错')
    } else if (err.request) {
      console.log('请求时报错')
    } else {
      console.log('请求未发出')
    }
  }
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

:本博客仅供个人学习,如有错误、侵权敬请指出。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57116
推荐阅读
相关标签
  

闽ICP备14008679号