main.js 2.2 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
// 如果前端没有登录信息则直接拦截,如果有则判断后端是否正常登录(防止构造参数绕过)
E
Evan 已提交
23 24
router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
E
Evan 已提交
25 26 27 28
      if (store.state.user) {
        axios.get('/authentication').then(resp => {
          if (resp) next()
        })
E
Evan 已提交
29 30 31 32 33 34 35 36 37 38 39
      } else {
        next({
          path: 'login',
          query: {redirect: to.fullPath}
        })
      }
    } else {
      next()
    }
  }
)
E
Evan 已提交
40 41

// http request拦截器,为请求加上 token,测试用,没有必要
E
Evan 已提交
42
/* axios.interceptors.request.use(
E
Evan 已提交
43
  config => {
E
Evan 已提交
44 45
    // 输出当前状态下的 token
    // console.log(store.state.user.token)
E
Evan 已提交
46
    if (store.state.user.token) {
E
Evan 已提交
47
      // 判断当前是否存在token,如果存在的话,则每个http header都加上token
E
Evan 已提交
48 49
      // config.headers.Token = `token ${JSON.stringify(store.state.user.token)}`
      config.headers.Token = JSON.stringify(store.state.user.token)
E
Evan 已提交
50 51
    } else {
      config.headers.Token = null
E
Evan 已提交
52 53 54 55 56
    }
    return config
  },
  err => {
    return Promise.reject(err)
E
Evan 已提交
57
  }
E
Evan 已提交
58
) */
E
Evan 已提交
59 60 61 62 63 64 65

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
E
Evan 已提交
66 67 68 69 70 71
    console.log(error.response)
    if (error) {
      router.replace({
        path: 'login',
        query: {redirect: router.currentRoute.fullPath}
      })
E
Evan 已提交
72 73 74 75 76
    }
    // 返回接口返回的错误信息
    return Promise.reject(error.response.data)
  })

E
Evan 已提交
77 78 79
/* eslint-disable no-new */
new Vue({
  el: '#app',
80
  render: h => h(App),
E
Evan 已提交
81
  router,
E
Evan 已提交
82
  store,
E
Evan 已提交
83
  components: {App},
E
Evan 已提交
84 85
  template: '<App/>'
})