The basic idea
First of all, it is important to know that login is not just about taking the username and password through the interface and sending it to the back end (which is what I thought before). There are several aspects to consider
- For asynchronous login, obtain the token through the login interface
- Use vuEX state to manage tokens, user information, etc
- The token is processed by intercepting each request/response using the AXIos interceptor
❝
The token indicates that the user has logged in successfully. Each time the user requests data, the token is sent to the backend for authentication and the backend returns a status code to determine the login status of the current user
❞
- Use navigation guard for login interception
- Password transmission encryption (generally need to introduce third-party encryption, baidu)
“The following code is for reference only“
The basic implementation of login
Click the button to trigger the event submitForm login.vue file
methods: {
submitForm(formName) {
this.$refs[formName].validate(valid= > {
if(valid) {
this.$store
.dispatch("userLogin".this.ruleForm) .then((a)= > { // A successful login message is displayed this.$router.push("home"); }) .catch(response= > { // Failed to log in }); } } else { // ... } }) } } Copy the code
The store.dispatch method triggers an Action
actions: {
userLogin({ commit }, userInfo) {
return new Promise((resolve, reject) = > {
Execute the userLogin method immediately, as shown in the following code
userLogin(userInfo.username, userInfo.password).then(response= > {
const data = response.data.data // Commit mutation to change state commit('SET_TOKEN', data.token) / / call setToken purpose is to take the token stored in localStorage sessionStorage/cookie GetToken () is used to obtain the token value setToken(data.token) resolve() }).catch(error= > { reject(error) }) }) }, // ... } Copy the code
Axios interceptor
My interceptor directory is/SRC /utils/request.js
// Create an axios instance
const service = axios.create({
baseURL: '/api'.// Configure according to the project
timeout: 5000 // Request timeout
})
// Request interceptor, add token to request header service.interceptors.request.use(config= > { if (store.state.user.myToken) { // Get the token from the store state // config.headers.' Name of token received by backend ' config.headers.myToken = store.state.user.myToken } return config }, error => { Promise.reject(error) }) // Respone interceptor service.interceptors.response.use(response= > { const res = response.data if (res.errno === 501) { // MessageBox is a component of elementUI MessageBox.alert('System is not logged in, please log in'.'wrong', { confirmButtonText: 'sure'. type: 'error' }).then((a)= > { / / logout }) return Promise.reject('error') } else if (res.errno === 502) { // Write similar } else { return response } }, error => { // Message is a component of elementUI Message({ message: 'Unknown error'. type: 'error'. duration: 5 * 1000 }) return Promise.reject(error) }) export default service Copy the code
The userLogin() directory/SRC/API /login.js corresponds to login.vue and stores the request code for easy maintenance
// Import the interceptor above
import request from '@/utils/request'
export function userLogin(username, password) {
const data = {
username, password } return request({ url: '/login'. method: 'post'. data }) } Copy the code
Navigation guard
Add meta: {requireAuth: true} to routes that require login
export default new Router({
mode: 'history'. routes: [
// ...
{
path: '/login'. name: 'login'. component: login, beforeEach: (to, from, next) = > { if (to.meta.requireAuth) { // Determine whether the login permission is required // Check whether there is a token if (store.state.user.myToken) { next() // Release when the conditions are met } else { next('/login') } } else { next() } } }, ] }) Copy the code
conclusion
This is the general process for logging in using vuex + AXIos interceptor + navigation Guard. It is not difficult to log out, just go through the interface to empty the local token. Here are some questions and answers
- Why vuex
❝
Because user information obtained through login is used in multiple components, using VUex to access variables directly through state or getters is convenient. But don’t use Vuex just for the sake of using it
❞
- Since using vuex why store token into localStorage/sessionStorage/cookie
❝
Because the refresh causes variables in vuex’s state to reset to their original values (” variable values will be lost “)
❞
- So why vuex?
❝
. That was answered
❞
[end]
This article is formatted using MDNICE