Vue項目請求頭添加token

一.調登陸接口後端返會token,將token存儲到sessionStorage和vuex中vue

1.login.vueios

<template>
  <div class="logcontainer"> 
          <div class="user-title">
            <p>用戶登陸</p>
          </div>         
          <div class="user-body">       
                <input  v-model="loginForm.username" placeholder="請輸入用戶名/手機號" />
                <p class="user-error" v-if="!loginForm.username&&none">用戶名/手機號不能爲空</p>
                <input type="password" v-model="loginForm.password"  placeholder="請輸入密碼" />
                <p class="password-error" v-if="!loginForm.password&&none">密碼不能爲空</p>
                <button type="submit"  @click="loginIn" >登陸</button>          
          </div>       
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import axios from "axios"
import qs from "qs"
export default {
    data(){
        return{ 
          none: false,     
          loginForm: {
            username: '',
            password: ''
          }
        }
    },
    methods:{  
       ...mapMutations(['changeLogin']),
      loginIn(){  
        this.none=true        
         let _this = this; 
        if (!this.loginForm.username || !this.loginForm.password) {
           return ''   
       }else{
        let para={
          loginName:this.loginForm.username,       
          passWord:this.loginForm.password
        };
        axios.post(`${axios.defaults.baseURL7}/login`,qs.stringify(para))
        .then(res=>{
           if(res.data.status){
           _this.userToken=res.data.data
            // 將用戶token保存到vuex中
          _this.changeLogin({ Authorization: _this.userToken });
         this.$router.push({path:"/home"})
           }else{
              this.$message.error(res.data.msg)
           }
        })   
      }         
      }          
      }
}
</script>
 
2.store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: { 
      // 存儲token
    Authorization: sessionStorage.getItem('Authorization') ? sessionStorage.getItem('Authorization') : ''  
  },
  mutations: {
     // 修改token,並將token存入localStorage
    changeLogin (state, user) {
      state.Authorization = user.Authorization;
      sessionStorage.setItem('Authorization', user.Authorization);
    }
  }
})
2、main.js中請求頭添加token
// 在請求頭中加token
axios.interceptors.request.use(
  config => {
  // 判斷是否存在token,若是存在的話,則每一個http header都加上token
    let token = sessionStorage.getItem('Authorization')
    if (!config.headers.hasOwnProperty('Authorization') && token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });
3、路由導航守衛
1.在router.js中添加
import Vue from 'vue';
import Router from 'vue-router';
import login from '@/components/login';
import home from '@/components/home'; 
Vue.use(Router); 
const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/home',
      name: 'home',
      component: home
    }
  ]
});
 
//導航守衛
// 使用 router.beforeEach 註冊一個全局前置守衛,判斷用戶是否登錄
router.beforeEach((to, from, next) => {
  //debugger
  if (to.path === '/login') {
    next();
  } else {
    let token = sessionStorage.getItem('Authorization');
    if (!token) {
      next('/login');
    } else {
      next();
    }
  }
});
export default router;
相關文章
相關標籤/搜索