In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "vue acquires token how to achieve token login". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The idea of using token for login authentication is roughly as follows:
1. When logging in for the first time, the front end calls the interface of the back end to pass the user name and password to the back end.
2. The backend receives the request, verifies the user name and password, and returns a token value to the front end after successful verification.
3. The front end receives the token value passed by the back end and stores the token in the local loaclStorage and vuex. (this project uses the vue framework and uses vuex global state management)
4. Each time the front end redirects the route, it determines whether there is a token in the localStorage. If not, it jumps to the login page, and if so, to the corresponding page.
5. Separate a common request interface method. Every time a request is called to the backend interface, token is placed in the request header.
6. The backend determines whether there is a token in the request header. If there is a token, it gets the token and verifies the token. If the verification succeeds, it returns the data. If the verification fails (for example, the token expires), it returns a status code to the frontend, which is generally 401. If there is no token in the request header, it also returns 401 (step 6 is done by the backend. The frontend only needs to deal with the status returned by the backend accordingly).
7. If the status code returned from the front end to the background is 401, clear token and jump to the login page.
Practical steps
1. Add global methods to save and delete token in all store.js files in the store in the project.
/ / the method of adding and removing token in all mutation in store.js import Vue from 'vue'import Vuex from' vuex'Vue.use (Vuex) const state = {/ / globally managed data store isLogin:'0', ser:null, token:localStorage.getItem ('token')? LocalStorage.getItem ('token'):', / / token} Export default new Vuex.Store ({state, getters: {/ / getStorage (state) listening for data changes) {/ / get locally stored login information if (! state.token) {state.token = JSON.parse (localStorage.getItem (key))} return state.token}} Mutations: {$_ setToken (state, value) {/ / set storage token state.token = value LocalStorage.setItem ('token', value);}, $_ removeStorage (state, value) {/ / delete token localStorage.removeItem (' token');},}})
2. After successfully calling the API for the login method on the login page (login.vue), store the token in the local storage localStorage.
/ / login.vue page methods: {loginFun () {this.$api.post ('requested backend API link', {data: {userId:this.user, / / login name userPwd:this.psw / / login password}}) .then ((res) = > {if (res.data.status = = 200) {var userInfo = res.data.data) This.$store.commit ('$_ setToken', userInfo.token); Toast ({message: 'login successful', type: 'success',duration: 1500}); / / ui pop-up prompt this.$router.push ({name:'homePage'}) / / Jump to the home page} else {Toast ({message: res.data.message, duration: 1500}); / / ui pop-up prompt}})}
3. Add a request interceptor to main.js and add token to the request header.
Import Vue from 'vue'import App from'. / App.vue'import router from'. / router/router'import store from'. / store/store'import PublicFun from'. / utils/publicFun' / / Public method import'. / mintUi' / / introduce mintUi build on demand if you need to configure to mintUi.js to configure import'@ / assets/mui/css/mui.css' / / mui.css style / * introduce axios plug-in * / import axios from 'axios'Vue.prototype.$http = axios / / Global route constructor to determine whether to log in and jump to the page router.beforeEach ((to, from, next) = > {if (to.matched.some (m = > m.meta.requireAuth)) {/ / need to log in to if (window.localStorage.token & & window.localStorage.isLogin ='1') {next ()} else if (to.path! = ='/ login') {let token = window.localStorage.token If (token = 'null' | | token =''| | token = undefined) {next ({path:'/ login'}) Toast ({message: 'detect that you are not logged in, please log in and do so!' , duration: 1500})} else {next ()}} else {/ / No login next ()}}) / / configure public urlAxios.defaults.baseURL = "http://www.sinya.online/api/"// add request interceptor axios.interceptors.request.use (config = > {if (store.state.token) {config.headers.common ['token'] = store.state.token} return config) }, error= > {/ / what to do with request errors return Promise.reject (error);}) / / http reponse response interceptor axios.interceptors.response.use (response = > {return response;}, error= > {if (error.response) {case (error.response.status) {case 401: localStorage.removeItem ('token')) Router.replace ({path:'/ views/login', query: {redirect: router.currentRoute.fullPath} / / Jump to browse the current page} after a successful login)}) Vue.prototype.$publicFun = PublicFun / / Mount the global public method Vue.prototype.$apps = Apps / / app.js public method Vue.config.productionTip = falsenew Vue ({router, store Render: h = > h (App)}). $mount ('# app')
See token
When you quit,
ReturnFun () {/ / logon MessageBox.confirm (this.lang.logoutTip) .then (action = > {this.$store.commit ('$_ removeStorage'); / / clear login information this.$router.push ({name:'login'}); Toast ({message:this.lang.logoutSuccess, duration: 1500}) }). Catch (() = > {})} "how to achieve token login when vue gets token" is introduced here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.