Do a simple login authentication function with vue.
Project directory structure is as follows:
Login Components
After a successful login to do local storage and store to store, and jump.
Login.vue key code:
handleLogin the async (E) { e.preventDefault (); the let parmas = { username: the this .model.username, passwold: the this .model.passwold }; const RES = the await the this $ http.get ( "/ API / Login." , parmas); const {code, token, Massage} = res.data; // code == ' 0' indicates the login is successful, local storage, and the storage and store jump. // else pops up an error message IF (code == "0" ) { the this $ store.commit ( "setToken." , res.data.token); localStorage.setItem ( "token", Token); // . If authentication is required to jump from the pages to the login page redirect = this $ route.query.redirect, if it is to jump directly to the login page click Login, then = redirect '/' const redirect = the this . $ route.query.redirect || "/" ; the this $ router.push (the redirect);. } the else { const Toast = the this $ createToast ({. Time: 2000 , TXT: Massage || "Login failed" , type: "error" }); toast.show (); } }
store
In the Login component in token persistent data processing done at login, refresh the page to prevent the loss of token. The time to store in the token initial value to be taken
store.js key code:
Vue from Import 'VUE' Import Vuex from 'vuex' Vue.use (Vuex) Export default new new Vuex.Store ({ State: { // token data persistence, refresh the page to prevent the loss of token: localStorage.getItem ( 'token') || '' }, mutations: { setToken (State, token) { state.token = token } }, Actions: { }, getters: { // The token is present, calculated properties set isLogin isLogin (State) { return ! ! state.token } } })
router
routes [] in a mate.auth to identify the need for authentication. router.beforeEach to be a global routing guard, to operate differently depending on whether authentication is needed and whether it has logged in.
router.js Code:
import Vue from 'vue' import Router from 'vue-router' import Home from './views/Home.vue' import Login from './views/Login.vue'; import store from './store'; Vue.use(Router) const router = new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'home', component: Home }, { path: '/login', name: 'login', Component: the Login }, { path: '/ About' , name: 'About' , Meta: {the auth: to true }, // About login authentication needs to be done Component: () => Import ( / * webpackChunkName: "About " * / './views/About.vue' ) } ] }) router.beforeEach ((to, from, Next) => { // to.meta.auth sound indicates to do log // unwanted direct the Next IF (to.meta.auth) { // store.state.token representation has logged directly the Next //Not logged jump to / login and easy to carry redirect login parameters jump directly to to.path IF (store.state.token) { Next (); } the else { Next ({ path: '/ login' , Query: { the redirect: to.path} }) } } the else { Next (); } }) Export default Router;
axios interception
axios.interceptors.request.use axios intercept all http requests, if the token is present, into the request header. In response axios of axios.interceptors.response.use interception, and if the token fails, remove and store the local cache memory and jump to the login page.
http-interceptors.js Code:
Axios from Import "Axios" ; Import from Store "./store" ; Import from Router "./router" ; // intercept all Axios http requests, in advance token into the request header axios.interceptors.request.use (config => { IF (store.state.token) { // If the token is present, then the header into the request config.headers.token = store.state.token; } return config; }); // response blocker pretreatment response advance axios.interceptors.response.use ( Response => { // if code is -1, indicating that the user has been canceled or expired token // this case need to login again, and also clear the local cache store data information and if(== 200 is Response.Status ) { const Data = response.data; IF (data.code == -1 ) { logoutFun () } } return Response; }, ERR => { IF (== err.response.status = 401) { // unauthorized logoutFun () } } ); function logoutFun () { // clear the local cache and store the token in the token store.commit ( "setToken", "" ); localStorage.removeItem ( "token " ); //Go to the login page, and the page carrying the route when the user exits or token fails, jump directly to this page after login convenience. router.push ({ path: "/ Login" , Query: { the redirect: router.currentRoute.path } }); }
app.use ((REQ, RES, Next) => { // only make a request to intercept the processing beginning api IF (/ ^ \ / api / .test (req.path)) { IF (req.path == ' / API / Login '|| req.headers.token) { Next (); } the else { // error status code 401 res.sendStatus (' 401 ' ) Next (); } } the else { Next (); } })