vue项目实现登录(sessionStorage 存储 token)
生活随笔
收集整理的這篇文章主要介紹了
vue项目实现登录(sessionStorage 存储 token)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前提參考:vue項(xiàng)目封裝axios
思路:
// 1, 前端校驗(yàn),校驗(yàn)成功后向后臺(tái)傳用戶名和密碼(每次請(qǐng)求接口都要傳 token)
// 2, 后端收到請(qǐng)求,驗(yàn)證用戶名和密碼,驗(yàn)證成功,生成 token 返回給前端
// 3, 前端拿到token,將token存儲(chǔ)到sessionStorage
// 4, 跳轉(zhuǎn)路由,就判斷 localStroage 中有無(wú) token ,沒有就跳轉(zhuǎn)到登錄頁(yè)面,有則跳轉(zhuǎn)到對(duì)應(yīng)路由頁(yè)面
// 5, 后端判斷請(qǐng)求頭中有無(wú)token,有token,就拿到token并驗(yàn)證token,驗(yàn)證成功就返回?cái)?shù)據(jù),驗(yàn)證失敗(例如:token過(guò)期)就返回401,請(qǐng)求頭中沒有token也返回401
// 6, 如果前端拿到狀態(tài)碼為401/退出登錄,就清除token信息并跳轉(zhuǎn)到登錄頁(yè)面
request.js
//http request 攔截器 instance.interceptors.request.use(config => {let token = sessionStorage.getItem('token')if(token == null){// 首次登錄config.headers.client_id = 'jeecp'config.headers.client_secret = 'webApp'}else{config.headers.Authorization = 'Bearer '+ token}return config},err => {return Promise.reject(err)} )api.js
// 登錄loginInfor(Information){return post('/api-auth/oauth/user/token' ,{username: Information.username,password: Information.password,})},登錄前端頁(yè)面
<template><el-container id="login"><el-aside width="70%"><p class="welcome">智能環(huán)境照明子系統(tǒng)歡迎您</p></el-aside><el-main><p>智能環(huán)境照明子系統(tǒng)</p><el-form ref="Form" :model="loginForms" :rules="loginRules" label-width="80px"><el-form-item prop="username"><el-input v-model="loginForms.username"><template slot="prepend"><i class="el-icon-user"></i></template></el-input></el-form-item><el-form-item prop="password"><el-input v-model="loginForms.password"><template slot="prepend"><i class="el-icon-goods"></i></template></el-input></el-form-item><el-button round @click.native.prevent="submit">登陸</el-button></el-form></el-main></el-container> </template> <style scoped> #login{width: 100%;height: 100%; }#login .el-aside{height: 100%;background-image: url('~@/assets/img/login_bg.png');position: relative;background-size: 100% 100%;background-repeat: no-repeat; } #login .el-aside .welcome{text-align: center;margin: 0 auto;position: absolute;top: 50%;transform: translateY(-50%);left: 49%;transform: translateX(-50%);font-size: 40px;color: #fff; } #login .el-main{padding: 0;background-color: rgba(77, 120, 223, 1); } #login .el-main p{color: #fff;font-size: 30px;margin-top: 45%;margin-bottom: 10%; }#login .el-main .el-input-group{width: 70%;/* margin: 0 15% 30px 15%; */ } #login .el-main .el-button{width: 35%;color: rgba(77, 120, 223, 1); } @media screen and (min-width: 1600px) and (max-width: 1920px) {#login .el-main p{margin-top: 67%;} } @media screen and (min-width: 1400px) and (max-width: 1600px) {#login .el-main p{margin-top: 65%;} } </style> <style> *{padding: 0;margin: 0; } </style> <script> import $ from "jquery" export default {data (){return {loginForms:{username: 'fox',password: '123456'},loginRules: {username: [{ required: true, trigger: 'blur', message: '用戶名不能為空' }],password: [{ required: true, trigger: 'blur', message: '密碼不能為空' }]}}},mounted() {$('#app').height($(window).height())$('.el-form-item__content').css("margin-left", "0")},methods: {// 重置登錄表單resetLoginForm() {this.$refs.Form.resetFields()},// 登錄submit(){this.$router.push("/index");// 測(cè)試表單數(shù)據(jù)校驗(yàn) Form 要和 表單的ref的名稱一致this.$refs.Form.validate(valid => {// console.log('校驗(yàn)結(jié)果: ' + valid)if (!valid) {console.log("參數(shù)驗(yàn)證失敗")return}// 校驗(yàn)成功this.$api.loginInfor(this.loginForms).then(res => {// console.log('請(qǐng)求結(jié)果:', res)if (res.code !== '000000') {// console.log("登錄失敗")return}else{console.log("token", res.data.access_token)// token放入 sessionStoragewindow.sessionStorage.setItem('token', res.data.access_token)// 跳轉(zhuǎn)到首頁(yè)this.$router.push({path: "/index"});}}).catch(err => {console.log(err)})})}} } </script>路由 index.js
// 導(dǎo)航守衛(wèi) // 使用 router.beforeEach 注冊(cè)一個(gè)全局前置守衛(wèi),判斷用戶是否登陸 router.beforeEach((to, from, next) => {// to 將要訪問(wèn)的路徑// from 從哪里跳轉(zhuǎn)來(lái)// next 放行//跳轉(zhuǎn)到登錄頁(yè)面直接放行if (to.path === '/login') {next();} else {// 獲取token,看是否有token,有token放行const token = window.sessionStorage.getItem("token")if (!token) {next('/login')return;} else{// 放行next();}} });總結(jié)
以上是生活随笔為你收集整理的vue项目实现登录(sessionStorage 存储 token)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: v-for中用elementUI实现分页
- 下一篇: html5倒计时秒杀怎么做,vue 设