main.js 2.4 KB
Newer Older
E
Evan 已提交
1 2 3 4 5 6 7 8 9
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
E
Evan 已提交
10
import store from './store'
E
Evan 已提交
11 12 13

var axios = require('axios')
axios.defaults.baseURL = 'http://localhost:8443/api'
E
Evan 已提交
14
// 使请求带上凭证信息
15
axios.defaults.withCredentials = true
E
Evan 已提交
16 17 18 19 20 21

Vue.prototype.$axios = axios
Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(mavonEditor)

E
Evan 已提交
22 23 24 25 26
// 页面刷新时,重新赋值token,也可直接在 store 里设置 token 默认值
// if (window.localStorage.getItem('token')) {
//   store.commit('login', window.localStorage.getItem('token'))
// }

E
Evan 已提交
27 28
router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
E
Evan 已提交
29
      if (store.state.user.token) {
30
        axios.post('/authentication')
E
Evan 已提交
31 32 33 34 35 36 37 38 39 40 41 42
        next()
      } else {
        next({
          path: 'login',
          query: {redirect: to.fullPath}
        })
      }
    } else {
      next()
    }
  }
)
E
Evan 已提交
43
// http request拦截器,会先于state的更新执行,以保证发送logout请求时也带上正确的token
E
Evan 已提交
44 45
axios.interceptors.request.use(
  config => {
E
Evan 已提交
46 47
    // 输出当前状态下的 token
    // console.log(store.state.user.token)
E
Evan 已提交
48
    if (store.state.user.token) {
E
Evan 已提交
49
      // 判断当前是否存在token,如果存在的话,则每个http header都加上token
E
Evan 已提交
50 51
      // config.headers.Token = `token ${JSON.stringify(store.state.user.token)}`
      config.headers.Token = JSON.stringify(store.state.user.token)
E
Evan 已提交
52 53
    } else {
      config.headers.Token = null
E
Evan 已提交
54 55 56 57 58
    }
    return config
  },
  err => {
    return Promise.reject(err)
E
Evan 已提交
59 60
  }
  )
E
Evan 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          store.commit('logout')
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          })
      }
    }
    // 返回接口返回的错误信息
    return Promise.reject(error.response.data)
  })

E
Evan 已提交
83 84 85
/* eslint-disable no-new */
new Vue({
  el: '#app',
86
  render: h => h(App),
E
Evan 已提交
87
  router,
E
Evan 已提交
88
  store,
E
Evan 已提交
89 90 91
  components: { App },
  template: '<App/>'
})