1. 程式人生 > 程式設計 >Vue專案中token驗證登入(前端部分)

Vue專案中token驗證登入(前端部分)

本文例項為大家分享了專案中token驗證登入的具體程式碼,供大家參考,具體內容如下

1、前言

最近在做畢業設計,我是做後端的,前端並不是很懂,看vue這個框架看了近兩個禮拜才有點入門的感覺,所以這篇文章寫的可能不怎麼好,僅作記錄,有什麼不對或不足的地方歡迎大神指出。

2、問題

做一個登入介面,我選擇的是用token進行驗證登入,我用的前端框架是Vue. 和 element-ui,如何在vue 中使用token進行驗證登入。

3、思考

1、利用token進行驗證登入,使用者進行登入操作時,後臺會生成一個token返回給前端,由前端 將這個token放到請求頭中(這個是百度的,一般都是放在請求頭),並且此後呼叫介面都要把token放到請求的請求頭傳回給後臺;

2、使用者登入後,前端需要把token儲存下來,後面傳送請求的時候在拿出來;
3、在傳送每個請求時都要把token加到請求頭裡,寫一個全域性的攔截器。

4、記錄和說明

1、 在src資料夾(我的vue專案是用vue-cli 腳手架建立的)下建立一個store資料夾,在store中建立一個index.js

Vue專案中token驗證登入(前端部分)

2、src/store/index.js

import Vue form 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
 state: {
  token: localStorage.getItem('token') ? localStorage.getItem('token') : ''
 },mutotions: {
  setToken (state,token) {
   state.token =token;
   localStorage.setItem("token",token.token);
  },delToken (state) {
   state.token = '';
   localStorage.removeItem("token");
  }
 }
})

export default store;

說明:

(1)在寫src/store/index.js 裡的內容之前,要在你的專案裡安裝Vuex ,這裡只提供npm的安裝方法,在專案根目錄處開啟cmd 輸入下面的命令,後回車

npm install vuex --save

(2) 在這個store/store/index.js中 這段程式碼token.token,是因為在login.vue中呼叫這個放法傳進來的是一個物件(即使你覺的你傳進來的是一個字串,不知道為什麼會被放到object裡去),傳進來的物件裡有token這個屬性

localStorage.setItem("token",token.token);

3、src/main.js

// 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 App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.'
import axios from 'axios'
import promise from 'es6-promise'
import store from './store/index'
promise.polyfill()

Vue.use(ElementUI)
Vue.config.productionTip = false
 

axios.defaults.baseURL= 'http://192.168.80.152:8088'
axios.defaults.headers.post['Content-Type'] = "application/json"
axios.defaults.withCredentials = true
axios.defaults.headers.common['Authorization'] = store.state.token
Vue.prototype.$axios = axios
 

/* eslint-disable no-new */
new Vue({
  el: '#app',router,store,components: { App },template: '<App/>'
});

// 新增請求攔截器
axios.interceptors.request.use(config => {
// 在傳送請求之前做些什麼
//判斷是否存在token,如果存在將每個頁面header都新增token
  if(store.state.token){
    config.headers.common['Authorization']=store.state.token.token
  }

  return config;
},error => {
// 對請求錯誤做些什麼
  return Promise.reject(error);
});

// http response 攔截器
axios.interceptors.response.use(
  response => {

    return response;
  },error => {

    if (error.response) {
      switcuEGChh (error.response.status) {
        case 401:
          this.$store.commit('del_token');
          router.replace({
            path: '/login',query: {redirect: router.currentRoute.fullPath}//登入成功後跳入瀏覽的當前頁面
          })
      }
    }
    return Promise.reject(error.response.data)
  });

說明

(1)這個是全部的程式碼,不一定都和這個一樣,下面說說用token驗證,src/main.js中要配置那些東西
(2)

import store from './store/index'

上面的程式碼是將之前寫的src/store/index.js匯入到main.js中

new Vue({
  el: '#app',template: '<App/>'
});

上述程式碼的store是將store掛載到Vue上,後面可以用this.$store 來獲取store

(3)

// 新增請求攔截器
axios.interceptors.request.use(config => {
// 在傳送請求之前做些什麼
//判斷是否存在token,如果存在將每個頁面header都新增token
  if(store.state.token){
    config.headers.common['Authorization']=store.state.token.token
  }

  return config;
},error => {
// 對請求錯誤做些什麼
  return Promise.reject(error);
});

// http response 攔截器
axios.interceptors.rwww.cppcns.comesponse.use(
  response => {

    return response;
  },error => {

    if (error.response) {
      switch (error.response.status) {
        case 401:
          this.$store.commit('del_token');
          router.replace({
            path: '/login',query: {redirect: router.currentRoute.fullPath}//登入成功後跳入瀏覽的當前頁面
          })
      }
    }
    return Promise.reject(error.response.data)
  });

上述程式碼就是請求攔截器,將token放到請求的請求頭中

4、src/router/index.js

router.beforeEach((to,from,next) => {
  if(to.path === '/login') {
    next();
  } else {
    let token = localStorage.getItem('token');
    if(token === 'null' || token === '') {
      next('/login');
    }else {
      next();
    }
 uEGCh }
});

說明

(1)上述程式碼是src/router/index.js 的配置 router 要暴露出來,程式碼中有export default

**5、src/components/login/login.vue **

//在這個元件script標籤的export default上面引入一個東西
 import { mapMutations } from 'vuex';
//這是methods部分
 methods: {

      ...mapMutations(['setToken']),login(form){


        let _this = this;
        if(form.phone === "" || form.password === ""){
          _this.$message.error("請輸入手機號或密碼");
        }else {
          this.$axios.post(`/user/check/login`,_this.form).then(res => {
            var code = res.data.code;
            var mes = res.data.message;
            if(code === 1){
             /* storage.setItem("token",res.data.data);
              _this.token = res.data.data;*/
             // _this.setToken({Authorization: _this.token})
             // console.log("success");
              _this.$message.success('登入成功');
              _this.token = res.data.data;
              _this.setToken({token: _this.token});
              _this.$router.push({path:"/home"});

              var storage = window.localStorage;
              //alert(storage.getItem("token"));

              if(this.$store.state.token) {
                this.$router.push('/home');
                console.log(this.$store.state.token.token);
              } else {
                this.$router.replace('/login');
              }

            }else{
              _this.$message.error(mes);
            }
          }).catch(function(err){
            console.log(err);
            _this.$message.error("登入錯誤,請聯絡程式開發人員!!");

          })
        }

      }
     }

說明

(1)

let _this = this;

上述程式碼是將this放在_this這個變數中 ,函式有普通函式:function(){} 和箭頭函式
普通函式的this是指當前物件的引用,這裡的當前物件是不確定的,箭頭函式的this是全域性的一個this 代表的物件是不可變的,任何方式不可以改變他,具體的區別參見:箭頭函式和普通函式的區別

 _this.setToken({token: _this.token});

上述程式碼就是呼叫src/store/index.js中的setToken()方法,之所以可以用_this呼叫是因為之前在src/main.js中將store掛載在vue上了

...mapMutations(['setToken']),

src/components/login/login.vue 中login()方法的前面有這樣一段程式碼,不知道是幹什麼的,可能是指定 score 中的方法, 這是我根據裡面的引數猜的不一定對,希望能有大神指點一二

下面是參考的文章,都寫的很好

1、在vue中如何獲取token,並將token寫進header
2、Vue專案中實現使用者登入及token驗證

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。