About the communication between Vue and the server: how to implement login authentication

       With the popularity of front-end and back-end separation development models, Vue, as a lightweight JavaScript framework, is widely used in front-end development. Vue can communicate with the server to obtain data and perform authentication. This article will discuss how to implement the login authentication process and give corresponding code examples.

1. Sending and receiving of front-end login requests
In the Vue project, login is an important part of the interaction between the user and the server. After the user enters the user name and password, a login request is sent by calling the back-end interface, and the server verifies the user's information and returns the corresponding result.

Code example:
First, create a new login component Login.vue in the Vue project:

<template>
  <div class="login-form">
    <input type="text" v-model="username" placeholder="请输入用户名" />
    <input type="password" v-model="password" placeholder="请输入密码" />
    <button @click="login">登录</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    login() {
      // 发送登录请求
      axios.post('/api/login', {
        username: this.username,
        password: this.password,
      })
        .then((response) => {
          console.log(response.data);
          // 处理登录成功的逻辑
        })
        .catch((error) => {
          console.log(error.message);
          // 处理登录失败的逻辑
        });
    },
  },
};
</script>

 

In the above code, we sent a POST request to /api/loginthe interface through the axios library, and passed the parameters of username and password. After receiving the response from the server, we can perform further processing according to the corresponding result.

2. Server-side login verification
Next, we need to verify the login request on the server side. The server can use any back-end language to implement the logic of login verification. Here, we take Node.js as an example for illustration.

Code example:
Create a router.js file to handle routing logic:

const express = require('express');
const router = express.Router();

// 处理登录请求
router.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  
  // 在这里进行登录验证的逻辑
  if (username === 'admin' && password === '123456') {
    res.json({ success: true, message: '登录成功' });
  } else {
    res.status(401).json({ success: false, message: '用户名或密码错误' });
  }
});

module.exports = router;

 

In the above code, we created a routing object router through the express library, and defined /api/loginthe interface to receive POST requests. In this interface, we can perform login verification based on username and password. If the validation is successful, we return a success response, otherwise we return an error response with the appropriate error message.

3. The processing after the front-end login is successful
In the front-end, we can store the login status through state management (such as Vuex), so that other components can perform authentication operations. After the login is successful, we can save the user's login status in Vuex, and jump to the corresponding page.

Code example:
first instantiate Vuex in main.js (or other entry files):

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    isLoggedIn: false, // 默认未登录
  },
  mutations: {
    login(state) {
      state.isLoggedIn = true;
    },
    logout(state) {
      state.isLoggedIn = false;
    },
  },
});

Vue.config.productionTip = false;

new Vue({
  store,
  render: (h) => h(App),
}).$mount('#app');

 In the Login.vue component, after the login is successful, we call the login method of the store to set the login status to true and perform a page jump.

<script>
import { mapMutations } from 'vuex';

export default {
  // ...
  methods: {
    ...mapMutations(['login']), // 映射login方法为组件方法
    login() {
      axios.post('/api/login', {
        username: this.username,
        password: this.password,
      })
        .then((response) => {
          console.log(response.data);
          if (response.data.success) {
            this.login(); // 登录成功后调用store的login方法
            // 处理登录成功的逻辑
          } else {
            // 处理登录失败的逻辑
          }
        })
        .catch((error) => {
          console.log(error.message);
          // 处理登录失败的逻辑
        });
    },
  },
};
</script>

 In other components that require authentication, we can determine whether we have logged in by accessing the state of the store, so as to perform corresponding operations, for example:

computed: {
  isLoggedIn() {
    return this.$store.state.isLoggedIn;
  },
},

 

        Through the above steps, we have realized the login authentication process between Vue and the server. After the user enters the user name and password, the front end sends a login request to the server, and the server returns the corresponding result after verification. The front end processes the logic of successful or failed login based on the results, and performs authentication operations through state management.


       This article is only a brief discussion on the login authentication between Vue and server-side communication. In actual development, more issues such as verification, encryption, authentication, and user rights may be involved. It is hoped that the introduction of this article can help readers better understand the relevant knowledge of Vue and server-side communication, and provide some references for the development of front-end and back-end separation.

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/132247385