Front-end login logic summary notes

When writing the background management system, I learned the vue-element-admin source code and summarized the logon logic

Front-end login structure:

<el-form

  ref="loginForm"

  :rules='loginRules'

></el-form>



loginRules: {

    username: [{required: true.trigger: "blur".validator: validateUsername }

    ],

    password: [{required: true.trigger: "blur".validator: validatePassword }

    ]

  },

  

  

handleLogin() {

  this.$refs.loginForm.validate(valid= > {

    if (valid) {

      this.loading = true

      this.$store.dispatch('user/login'.this.loginForm)

        .then(() = > {

          this.$router.push({ path: this.redirect || '/'.query: this.otherQuery })

          this.loading = false

        })

        .catch(() = > {

          this.loading = false})}else {

      console.log('error submit!! ')

      return false}})}Copy the code

The front end calls the validate method of el-form to validate rules, and if the verification is passed, the user login information is forwarded to the VUEX User/Loginaction method for login verification, and if the login verification is passed, it will redirect to the redirect route. If redirect does not exist then go to the home page “/”

After handing over the user login information to vuex, the Action method gets the deconstructed username and password, calls the LOGIN method in the API, and passes the username and password in. After the request succeeds, the token in the response is obtained. Save it to vuex’s state state, then save the token in a Cookie, and err reject the exception if it fails

login({ commit }, userInfo) {

    const { username, password } = userInfo

    return new Promise((resolve, reject) = > {

      login({ username: username.trim(), password: password }).then(response= > {

        const { data } = response

        commit('SET_TOKEN', data.token)

        setToken(data.token)

        resolve()

      }).catch(error= > {

        reject(error)

      })

    })

}
Copy the code

Here the login function is a wrapped API, the request method is based on an AXIos-wrapped library, and the Vue-ele-admin is wrapped as a service. More on that later

import request from '@/utils/request'



export function login(data) {

  return request({

    url: 'Back-end login interface'.method: 'post',

    data

  })

}
Copy the code

Axios encapsulates the Service library

There are two types of interceptors in AXIos: request (request interceptor) and Response (response interceptor)

const service = axios.create({

    baseURL: process.env.VUE_APP_BASE_API,

    timeout: 5000

})

/ / request

service.interceptors.request.use(

    config= > {

        if(store.getters.token) {

            / / custom headers

            config.headers['X-Token'] = getToken()

        }

        return config

    },

    error= > {

        // Exception handling

        console.log(error)

        return Promise.reject(error)

    }

)

 / / response to intercept

service.interceptors.response.use(

response= > {

  const res = response.data

  if(res.code ! = =20000) {

    // If the status code returned is incorrect, this will be further determined and processed

   

    if (res.code === 50008 || res.code === 50012 || res.code === 50014) {

      // 50008: Illegal token;

      //50012: Other clients logged in;

      //50014: Token expired;

      / / the pop-up Message

      // to re-login

      }).then(() = > {

        store.dispatch('user/resetToken').then(() = > {

         // If the token is invalid, the token is refreshed and

         // Refresh the page

        location.reload()

        })

      })

}

    return Promise.reject(new Error(res.message || 'Error'))}else {

    return res

  }

},

  error= > {

      return Promise.reject(error)

  }

)
Copy the code

Let’s start by creating the Axios example, which helps us with some basic request functionality, and more importantly its two interceptors: Request interceptor and response interceptor. The advantage of setting request interceptor is that you can add a global level such as token to determine whether there is a login. If there is a token, you can add it to the request parameters.

Config parameters are as follows:

The benefit of setting the response interceptor is to intercept the response and do different processing according to the returned status code. Different status codes have different meanings. In this case, different processing needs to be done according to the status code returned by the interface request

Finally, summarize the process: the front-end authenticates the login information and gives the user login information to the action method of VUEX. Vuex calls the login API after getting the user information. After success, the user token is saved to the state state and saved to the Cookie. Although the whole process is relatively simple, but very practical!! And applicable to a very wide range, I write in the project to use the login words are basically so write, so understand the above written logic of the entire front-end login should be a little help to their own development