国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue+egg+jwt實(shí)現(xiàn)登錄驗(yàn)證的示例代碼

2024-05-06 15:39:17
字體:
供稿:網(wǎng)友

原理:vue前端登錄,提交賬號密碼給egg后端,后端比對信息后,使用jsonwebtoken對用戶信息進(jìn)行簽名生成token,之后通過cookie返回給vue前端,前端需要使用token里的信息就使用js-base64進(jìn)行token第二段解碼即可。

vue前端路由跳轉(zhuǎn),進(jìn)入路由前置守衛(wèi)檢測cookie中的token是否存在,不存在(已過期)則跳轉(zhuǎn)登錄,否則繼續(xù)執(zhí)行,然后在http攔截器里請求時(shí)存在token請求頭帶上token,后端未得到header則返回錯(cuò)誤碼,得到則用jsonwebtoken進(jìn)行驗(yàn)證,是時(shí)間錯(cuò)誤就從新發(fā)放token令牌,否則返回錯(cuò)誤碼,還要及時(shí)更新cookie時(shí)間,保證登錄態(tài).

vue前端main.js中:

import axios from 'axios';import cookie from './public/util';router.beforeEach((to, from, next) => { console.log('路由攔截') //判斷要去的路由有沒有requiresAuth if (to.meta.requiresAuth) {  let token = cookie.getCookie('token');  if (token) {   next();  } else {   next({    path: '/login'   });  } } else {  next(); //如果無需token,那么隨它去吧 }})// http request 攔截器axios.interceptors.request.use( config => {  let token = cookie.getCookie('token');  console.log(token)  if (token) { // 判斷是否存在token,如果存在的話,則每個(gè)http header都加上token   config.headers.authorization = `token ${token}`;  }  return config; }, err => {  return Promise.reject(err); }); // http response 攔截器axios.interceptors.response.use( response => {  return response; }, error => {  if (error.response) {   switch (error.response.status) {    case 401:     // 返回 401 清除token信息并跳轉(zhuǎn)到登錄頁面     router.replace({      path: '/login'     });   }  }  return Promise.reject(error.response.data);  // 返回接口返回的錯(cuò)誤信息 });Vue.prototype.$http = axios;

其中util.js中我封裝了操作cookie的方法

//獲取cookie、function getCookie(name) {  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");  if (arr = document.cookie.match(reg))   return (arr[2]);  else   return null;  }    //設(shè)置cookie,增加到vue實(shí)例方便全局調(diào)用function setCookie (c_name, value, expiredays) {  var exdate = new Date();  exdate.setDate(exdate.getDate() + expiredays);  document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());  };    //刪除cookiefunction delCookie (name) {  var exp = new Date();  exp.setTime(exp.getTime() - 1);  var cval = getCookie(name);  if (cval != null)   document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();  };  module.exports = {  getCookie:getCookie,  setCookie:setCookie,  delCookie:delCookie  }

路由中需要登錄才能訪問的頁面,應(yīng):

path:'/admin/manager',component:Page,name:'管理系統(tǒng)首頁',meta:{requiresAuth:true}

如果需要獲取token中的信息則:

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 临西县| 祥云县| 五原县| 台北县| 砚山县| 郎溪县| 长岭县| 扬中市| 青龙| 积石山| 大同市| 东安县| 剑阁县| 金门县| 长治市| 仪征市| 长子县| 满洲里市| 普宁市| 安丘市| 饶阳县| 含山县| 贞丰县| 昌乐县| 沈丘县| 盱眙县| 皮山县| 茶陵县| 建始县| 泰安市| 商都县| 固原市| 安吉县| 金乡县| 宁都县| 渭源县| 长汀县| 肥乡县| 平凉市| 丹寨县| 河津市|