preface

The separated development and independent deployment of the front and back ends provide great convenience to the front-end developers, but also bring new challenges.

Problems with front and rear end separation

  1. At the routing level, the switch and jump between modules need to be maintained independently by the front-end
  2. At the interface level, front-end and back-end data interactions are connected by interfaces (asynchronous)

This is important: the front end needs to perform permission control interception according to the user’s login state or role identity to display the corresponding function module or data.

Next, Brother Hu will share the principle and implementation of user log-in routing level and interface level interception based on Vue+VueRouter+Vuex+Axios in the actual project.

Routing level interception

  1. thinking
    • How to intercept

BeforeEach ((to, from,next) => {// next() passes, beforeEach(to, from,next) => { // next(false) disable, disallow access to the module})

  • Who stopped

    {path: 'user', name: 'user', Component: user, meta: {path: 'user', name: 'user', Component: user, meta: RequireAuth: true}}Copy the code
  1. Implementation scheme

    • Install the vue – the router

        npm i vue-router -D
      Copy the code
    • Define routes and route setting permission flags

      Import Vue from 'Vue' import VueRouter from 'vue-router' vuue. use(VueRouter) const router = new VueRouter({// routing rules Component: Home, children: [{path: '/', name: 'Home', // Routes: [{path: '/', name: 'Home', // routes: [{path: 'index', name: 'Index', Component: Index, // Define meta information meta: {// Permission validation flag false No verification interception requireAuth: false}}, {path: 'user', name: 'User', Component: User, meta: {// Permission validation flag true to verify interception requireAuth: true}}, {path: 'login', name: 'Login', Component: Login, meta: {// Permission verification flag false No verification interception requireAuth: false}}]}]})Copy the code
    • Permission interception decision

    The user login status is used as the symbol for login authentication

    const router = new VueRouter({ routes: [ // ... ] }) // Permission interception -beforeEach Routing hook function router. BeforeEach (to, from, Next) {// To destination routing object from source routing object if (to.mate.some (rocode => recode.meta.requireauth)) {/** * Login status - AixOS can be used to request, Pull server data to obtain user login status * It is strongly recommended to use localStorage or sessionStorage and VUEX to jointly manage user login status, so as to avoid pulling server interface to verify user login every time, which will consume additional requests to the server. Upgrade user experience * If logged in, update loginName stored in store -- check the following store configuration * If not logged in, go directly */ let isLogin = Logged in? // Perform interception if (! Next ({name: 'Login', replace: 'true', // redirectUrl Indicates the address of the hop after login. To.fullpath}) // Next (false) to window.loaction.href = 'window.location.href? RedirectUrl =' + to.fullPath next(false)} else {// Next ()} else {// Do not intercept, directly enter the path next()}}Copy the code

Interface level interception

  1. thinking

    • How to intercept

      Using axios interceptor: interceptors. Request. Use request interceptor interceptors. Response. Use response interceptorsCopy the code
    • Who stopped

      Set a specific interface address whitelist to determine the login permission of the user

      Not all interfaces need to be intercepted, for example: 1. Interfaces that send and obtain login information 2. Interface for sending registration information 3. Other interfaces that do not need user modeCopy the code
  2. Implementation scheme

    • Install axios

        npm i axios -D
      Copy the code
    • Introduce Axios and add interceptors

      Import axios from 'axios' import router from '@/router' // Import store from '@/store' const $HTTP = Axios.create ({// basic configuration item}) // Define interface address whitelist const allowUrls = ['/getUserInfo', '/addUserInfo'] // Request interceptor -- before sending a request, Determine whether there is any login information $HTTP. Interceptors. Resquest. Use ((config) = > {/ / config. The url is requested url address the if (allowUrls. Includes (config. Url)) { Let isLogin = locationstorage. getItem('isLogin') if (! isLogin || ! Store.state.loginname) {// Carry the current routing address, Jump login / / router. CurrentRoute. FullPath} else {return config}} else {/ / don't need to determine is returned directly config configuration return config}}) / / response interceptors $HTTP. Interceptors. Response. Use ((res) = > {/ / determine whether need to verify permissions if (allowUrls. Includes (res) config) url)) {/ / login - determine whether Let isLogin = locationStorage.getItem('isLogin') // Convention code 10011 indicates no login. If (! isLogin || ! Store. The state. The loginName | | res. Data. Code = = = 10011) {/ / carry when routing address, Jump to login / / router. CurrentRoute. FullPath} else {return config}} else {return res}})Copy the code

Data warehouse SOtre

  1. Download and install vuex

     npm i vuex -D
    Copy the code
  2. Configuring Related Items

    import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: Mutations: {upgrade (theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta, theta)Copy the code

Afterword.

The above is brother Hu today to share the content, like friends remember to collect, forward, click in look yo…

Brother Hu has words, a technology, feelings of brother Hu! Jingdong open platform chief front-end siege lion. Talk with you about the big front end, share front-end system architecture, framework implementation principles, the latest and most efficient technology practice!

Long press scan code attention, more handsome more beautiful yo!