每天一点点之vue框架开发 - axios拦截器的使用

<script>
import axios from 'axios'

export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    getImg () {
      axios.get('https://static.segmentfault.com/v-595f50ca/global/img/logo-b.svg')
        .then((response) => {
          console.log(response)
        }).catch((error) => {
          console.log(error)
        })
    },
    addInterceptors () {
      axios.interceptors.request.use(function (config) {
        // Do something before request is sent
        console.log('开始请求')
        console.log(`请求地址: ${config.url}`)
        return config
      }, function (error) {
        // Do something with request error
        console.log('请求失败')
        return Promise.reject(error)
      })
      axios.interceptors.response.use(function (config) {
        // Do something before request is sent
        console.log('接收响应')
        return config
      }, function (error) {
        // Do something with request error
        console.log('响应出错')
        return Promise.reject(error)
      })
    }
  },
  mounted () {
    this.addInterceptors()
    this.getImg()
  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/cap-rq/p/10149276.html