vue interception

```javascript
Import view from 'View'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css'
Vue.use (cells)
// Clear default style
import axios from 'axios'

// because the underlying principle Vue also to mount on the prototype js method, so we can mount a global axios
Vue.prototype.$http = axios;
// global configuration baseURL
axios.defaults.baseURL = 'http://www.litc.pro:9999/v1';
// add request interceptor
axios.interceptors.request.use(function (config) {
  // What to do before sending the request
  let token = localStorage.getItem('token')||''
  config.headers.Authorization = token
  return config;
}, function (error) {
  // What do request error
  return Promise.reject(error);
});

// add response interceptor
axios.interceptors.response.use(function (response) {
  // do something in response to data
  //console.log(response.data)
  response = response.data
  return response;
}, function (error) {
  // do something wrong response
  Vue.prototype. $ Message ({
    showClonse:true,
    type:'error',
    message:error.response.data.errMsg
  })
  return Promise.reject(error);
});
// navigation guard
router.beforeEach((to,from,next)=>{
let token = localStorage.getItem('token') || ''
// interception while logged in
//console.log(to.path)
// If you do not have to go to the token and is not signin page
if(token && to.path === '/signIn'){
  return next('/home')
}
if(token || to.path === '/signIn'){
  next()
}else{
  // If not logged in, you jump back /
  next('/')
}
})
Vue.config.productionTip = false


new view ({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
```

  

Guess you like

Origin www.cnblogs.com/tuziling/p/11770431.html