Home > Web Front-end > Vue.js > Analysis of communication between Vue and server: How to implement login authentication

Analysis of communication between Vue and server: How to implement login authentication

WBOY
Release: 2023-08-12 08:42:38
Original
1425 people have browsed it

Analysis of communication between Vue and server: How to implement login authentication

Analysis of communication between Vue and server: How to implement login authentication

Introduction:
With the popularity of the front-end and back-end separation development model, Vue as a A lightweight JavaScript framework widely used for 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 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 username and password, a login request is sent by calling the backend 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>
Copy after login

In the above code, we sent a POST request to through the axios library /api/login interface, and the parameters of username and password are passed. After receiving the server's response, we can perform further processing based on the corresponding results.

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

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;
Copy after login

In the above code, we create a routing object router through the express library, and define The /api/login interface is used to receive POST requests. In this interface, we can perform login verification based on user name and password. If the verification is successful, we return a success response, otherwise an error response containing the appropriate error message.

3. Processing after successful front-end login
On the front-end, we can store the login status through status management (such as Vuex) to facilitate other components to perform authentication operations. After successful login, we can save the user's login status to Vuex and jump to the corresponding page.

Code example:
First instantiate Vuex in main.js (or other entry file):

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');
Copy after login

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

<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>
Copy after login

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;
  },
},
Copy after login

Conclusion:
Passed In the above steps, we implemented the login authentication process between Vue and the server. After the user enters the username and password, the front-end sends a login request to the server. After verification, the server returns the corresponding result. The front end handles the logic of login success or failure based on the results, and performs authentication operations through status management.

Written at the end:
This article is only a simple discussion on the communication between Vue and the server to achieve login authentication. Actual development may also involve more verification, encryption, authentication, and user permissions. And other issues. 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 reference for front-end and back-end separation development.

The above is the detailed content of Analysis of communication between Vue and server: How to implement login authentication. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template