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

axios.defaults.timeout = 30000
9 10 11 12
console.log('NODE_ENV' + process.env.NODE_ENV)
if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = baseUrl.sjkgUrl
}
潘琦 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 => {
21
  let token = store.getters.access_token
潘琦 committed
22
  if (token) {
23
    // config.headers['Authorization'] = 'Bearer ' + token
潘琦 committed
24 25 26 27 28 29 30 31 32 33
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

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

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

export default axios