request.js 1.99 KB
Newer Older
潘琦 committed
1
import axios from 'axios'
潘琦 committed
2
import store from '../store'
潘琦 committed
3 4
import { Toast } from 'mint-ui'
import router from '@/router/index'
潘琦 committed
5
import { removeUrlParam } from '@/util/index'
潘琦 committed
6 7

axios.defaults.timeout = 30000
潘琦 committed
8 9 10 11 12
console.log('NODE_ENV' + process.env.NODE_ENV)
if (process.env.NODE_ENV === 'production') {
  let root = process.env.API_ROOT
  axios.defaults.baseURL = root // 开发服
}
潘琦 committed
13 14 15 16 17 18 19 20
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status // 默认的
}
// 跨域请求,允许保存cookie
axios.defaults.withCredentials = true
// request拦截器
axios.interceptors.request.use(config => {
潘琦 committed
21
  let token = store.getters.access_token
潘琦 committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
axios.interceptors.response.use(response => {
  const res = response.data ? response.data : response
  const status = Number(response.status) || 200
  console.log('response status:' + status)
  if (status !== 200) {
    if (status === 401) {
      Toast({
        message: '您因长时间逗留,验证已过期,正在刷新!',
        position: 'center',
        duration: 5 * 1000
      })
潘琦 committed
44 45 46
      store.dispatch('setToken', '')
      store.dispatch('setUserId', '')
      store.dispatch('setCode', '')
潘琦 committed
47
      setTimeout(function () {
潘琦 committed
48 49
        window.location.href = removeUrlParam('code')
      }, 4 * 1000)
潘琦 committed
50 51 52 53 54 55 56 57 58
    } else if (status === 403) {
      if (res.msg === '请先进行实名认证') { // 跳转至社区推荐页
        router.push({
          path: '/recommend'
        })
      }
    } else {
      return Promise.reject(new Error(res.msg))
    }
潘琦 committed
59 60 61 62 63
  } else if (res.code === 1) {
    if (!res.msg) {
      res.msg = '内部服务器错误[500]'
    }
    return Promise.reject(new Error(res.msg))
潘琦 committed
64 65 66 67 68 69 70 71 72
  }

  return res
}, error => {
  console.log('错误' + error)// for debug
  return Promise.reject(new Error(error))
})

export default axios