美文网首页
vue把token添加到请求头中

vue把token添加到请求头中

作者: 五四青年_4e7d | 来源:发表于2020-05-26 22:06 被阅读0次

    main.js中

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    
    
    import VueCookies from 'vue-cookies'    //设置cookie引入
    Vue.use(VueCookies)
    
    import Vant from 'vant';
    import 'vant/lib/index.css';
    import http from '../http';
    Vue.prototype.$http = http;
    Vue.use(Vant);
    
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      render: h => h(App)
    })
    
    

    index.js

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import HelloWorld from '@/components/HelloWorld'
    import Zhuce from '@/components/zhuce'   //注册
    import login  from '@/components/login'   //登录
    import userInfo  from '@/components/userInfo'   //个人中心
    
    Vue.use(VueRouter)
    
    const  routes = [
        {
          // path: '/',
          path: '/Zhuce',
          component: Zhuce
        },
        {
          path: '/login', 
          component:login
        },
        {
          path: '/userInfo', 
          component:userInfo,
          meta:{
            isToken:true
          }
        }
      ]
      const router =  new VueRouter({
        routes,
        mode:'history'
      })
    
      //设置路由导航拦截:
      router.beforeEach((to,from,next)=>{
        if(!localStorage.getItem('token') && !localStorage.getItem('id') && to.meta.isToken == true){
         router.push('/login')
         Vue.prototype.$toast.fail('请重新登录')
          return
        }
        next()
      })
      
    export default router
    
    

    http.js

    import axios from 'axios'
    import router from './src/router'
    import Vue from 'vue'
    
    const http = axios.create({
        baseURL: 'http://112.74.99.5:3000/web/api'
    })
    //请求拦截
    http.interceptors.request.use(function (config) {
        console.log(config)
        if(localStorage.getItem('token') && localStorage.getItem('id')){
            config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
        }
        return config
    }, function (error) {
        return Promise.reject(error)
    });
    //响应拦截
    http.interceptors.response.use(function (response) {
        return response
    }, function (error) {
        if(error.response.status == 401 || error.response.status == 402){
            router.push('/login')
            Vue.prototype.$toast.fail('请重新登录')
        }
        return Promise.reject(error)
    });
    export default http
    

    相关文章

      网友评论

          本文标题:vue把token添加到请求头中

          本文链接:https://www.haomeiwen.com/subject/htwsahtx.html