Vue添加请求拦截器

一、现象

统一处理错误及配置请求信息

二、解决

1、安装 axios  , 命令: npm install axios --save-dev

2、在根目录的config目录下新建文件 axios.js  ,内容如下:

import axios from 'axios'

// 配置默认的host,假如你的API host是:http://api.htmlx.club
axios.defaults.baseURL = 'http://api.htmlx.club'    

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  return config
}, function (error) {
  // 对请求错误做些什么
return Promise.reject(error)
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error)
});

3、在main.js中进行引用,并配置一个别名($ajax)来进行调用:

import axios from 'axios'
import '../config/axios'

Vue.prototype.$ajax = axios

如图:

4、应用,一个登录的post如:

this.$ajax({
  method: 'post',
  url: '/login',
  data: {
    'userName': 'xxx',
    'password': 'xxx'
  }
}).then(res => {
  console.log(res)
})

三、总结

统一处理方便

例:

使用iview框架,在main.js添加请求接口拦截器 loading

复制代码
axios.interceptors.request.use(function (config) {
  iView.LoadingBar.start()
  return config
}),function (error) {
  iView.LoadingBar.error()
  return Promise.reject(error)
}
axios.interceptors.response.use(function (config) {
  iView.LoadingBar.finish()
  return config
}),function (error) {
  iView.LoadingBar.error()
  return Promise.reject(error)
}
复制代码
复制代码
/**
 * @export
 * @param {any} request
 * @param {any} next
 * @returns
   */
import store from './vuex/store'
// 全局错误处理,全局loading
import { setLoading, setTip } from './vuex/actions/doc_actions'
export default function (request, next) {
  if (request.tip !== false) {
    setLoading(store, true)
  }
  next((res) => {
    setLoading(store, false)
    let data = JSON.parse(res.data)
    if (res.status === 0) {
      setTip(store, {
        text: '网络不给力,请稍后再试'
      })
    }
    if (!data.success) {
      setTip(store, {
        text: data.error_msg
      })
    }
  })
}
复制代码

猜你喜欢

转载自www.cnblogs.com/sweet-ice/p/10520375.html