文件引入

1
2
import Vue from 'vue'
import axios from 'axios'

全局参数

1
Vue.prototype.$http = axios

请求头Header

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
axios.interceptors.request.use(function (config) {
  config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  const token = localStorage.getItem('token')
  const TGC = getCookie('TGC')
  if (TGC) {
    config.headers.Authorization = TGC
  } else if (token) {
    config.headers.Authorization = token
  }
  return config
})

基本URL

1
axios.defaults.baseURL = 'https://xxx.com/' 

POST请求

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
Vue.prototype.$post = function (url, data) {
  let opt = {
    url: url,
    method: 'post',
    data: {
      request: data
    },
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  }
  return new Promise((resolve, reject) => {
    axios(opt)
      .then(res => {
        resolve(res)
      })
      .catch(res => {
        reject(res)
      })
  })
}

响应拦截

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
axios.interceptors.response.use(res => {
  if (res.data.resultcode === '-33') {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    router.push({
      path: '/login'
    })
  }
  return res
})