Vue中axios拦截器的封装

298 阅读1分钟

在JQuery中我们是这样通过ajax向后端发送请求的

$.ajax({
    url: url,
    type: post,
    headers: {
      'Content-Type': contentType,
      'access_token': token
    },
    data: data,
    dataType: json,
    async: true,
    beforeSend: function () {
      
    },
    success: function (res) {
      console.log(res)
    },
    complete: function () {
     
    }
  });

而在Vue中我们一般通过axios向后端发送ajax请求,而像token这样的数据我们应该怎么携带呢,这就用到axios的拦截器了

//存取token操作
const getToken = () =>{
    sessionStorage.getItem('token')
}
 const setToken = token =>{
    sessionStorage.setItem(token)
}
//判断是测试环境还是生产环境
export const baseUrl = (process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro)

class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl
  }

  interceptors(instance) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      const { data, status } = res
      if (data.code !== 1) {
        if (data.code === -14) {
          setToken('')
          router.push({ name: 'login' })
        } else {
          console.log('error')
        }
        throw new Error(data.msg)
      } else {
        return { data, status }
      }
    }, error => {
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    const apiAuth = getToken()
    if (apiAuth === false) {
      options = Object.assign({
        baseURL: this.baseUrl,
        headers: {}
      }, options)
    } else {
      options = Object.assign({
        baseURL: this.baseUrl,
        headers: {
          apiAuth: apiAuth
        },
        withCredentials: true
      }, options)
    }
    this.interceptors(instance)
    return instance(options)
  }
}

const api_axios = new HttpRequest(baseUrl)
export default api_axios