[project practice] implementation of login and registration business (front end + back end + database)

This example is based on Vue JS and mint UI implementation.

catalogue

1, Creation of database

2, Connection between back-end interface and database

3, Front end code implementation

1. Relevant codes of registration page

2. Effect of registration page

3. Relevant codes of login page

4. Landing page effect

4, Demo login

5, Project file structure

1, Creation of database

Navicat software is used here to create a new database reg_log.sql and data table reg_log;

In order to realize the registration business, we design five fields in the database: ID, user name, password, email and telephone number.

After creating and saving, you can find the database and empty table we just created in the database. So you can connect in the project.

**2, * * connection between back-end interface and database

server folder - > app js

// Load Express module
const express = require('express');

// MySQL module loading
const mysql = require('mysql');

// Load bodyParser module
const bodyParser = require('body-parser');

// Load MD5 module
const md5 = require('md5');

// Create MySQL connection pool
const pool = mysql.createPool({
  host: '127.0.0.1', //MySQL server address
  port: 3306, //MySQL server port number
  user: 'root', //User name of the database user
  password: '', //Database user password
  database: 'reg_log', //Database name
  connectionLimit: 20, //maximum connection
  charset: 'utf8' //Encoding method of database server
});

// Create server object
const server = express();

server.use(bodyParser.urlencoded({
  extended: false
}));


// Load CORS module
const cors = require('cors');

// Using CORS Middleware
server.use(cors({
  origin: ['http://localhost:8080', 'http://127.0.0.1:8080']
}));

//User registration interface
server.post('/register', (req, res) => {
  //console.log(md5('12345678'));
  // Get user name and password information
  let username = req.body.username;
  let password = req.body.password;
  //Search with username as the condition to ensure the uniqueness of the user name
  let sql = 'SELECT COUNT(id) AS count FROM reg_log WHERE username=?';
  pool.query(sql, [username], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // Insert user related information into the data table
      sql = 'INSERT reg_log(username,password) VALUES(?,MD5(?))';
      pool.query(sql, [username, password], (error, results) => {
        if (error) throw error;
        res.send({
          message: 'ok',
          code: 200
        });
      })
    } else {
      res.send({
        message: 'user exists',
        code: 201
      });
    }
  });
});

// User login interface
server.post('/login', (req, res) => {
  //Get user name and password information
  let username = req.body.username;
  let password = req.body.password;
  // SQL statement
  let sql = 'SELECT id,username FROM reg_log WHERE username=? AND password=MD5(?)';
  pool.query(sql, [username, password], (error, results) => {
    if (error) throw error;
    if (results.length == 0) { //Login failed
      res.send({
        message: 'login failed',
        code: 201
      });
    } else { //Login successful
      res.send({
        message: 'ok',
        code: 200,
        result: results[0]
      });
    }
  });

});

// Specifies the port number on which the server object listens
server.listen(3000, () => {
  console.log('server is running...');
});

**3, * * front end code implementation

1. Relevant codes of registration page

Project folder - > register vue

<template>
<!-- Registration page -->
  <div class="reg">
    <mt-header title="User registration">
      <router-link slot="left" to="/"> Return to home page </router-link>
      <router-link to="/login" slot="right">Go login</router-link>
    </mt-header>
    <mt-field
      type="text"
      label="user name"
      placeholder="enter one user name"
      v-model="name"
      :state="nameState"
      @blur.native.capture="checkName"></mt-field>
      <!-- @blur Out of focus, the input box is verified when the input is completed and moved to other places -->
    <mt-field
      type="password"
      label="password"
      placeholder="Please input a password"
      v-model="pwd"
      :state="pwdState"
      @blur.native.capture="checkPwd"></mt-field>
    <mt-field
      type="password"
      label="Confirm password"
      placeholder="Enter the password again"
      v-model="repwd"
      :state="repwdState"
      @blur.native.capture="checkrePwd"></mt-field>
    <mt-field
      label="mailbox"
      placeholder="Please enter email address"
      type="email"
      v-model="email"
      :state="emailState"
      @blur.native.capture="checkEmail"></mt-field>
    <mt-field
      label="cell-phone number"
      placeholder="Please enter your mobile number"
      type="tel"
      v-model="phone"
      :state="phoneState"
      @blur.native.capture="checkPhone"></mt-field>
    <mt-field
      label="birthday"
      placeholder="Please enter birthday"
      type="date"
      v-model="birthday"></mt-field>
    <mt-button class="btn" type="primary" size="large" @click="checkForm">register</mt-button>
  </div>
</template>

<style scope>
.reg .btn {
  background-color: #d86931;
  width: 190px;
  border-radius: 0;
  border: 0;
  margin: auto;
}
.reg .mint-cell-wrapper {
  line-height: 80px;
}
.reg {
  margin-top: 14%;
}

.reg .mint-header {
  background-color: #d86931;
}
.reg .btn {
  background-color: #d86931;
}
</style>

<script>
export default {
  data() {
    return {
      name: "", //Bidirectional data binding user name input box
      nameState: "", //Handle the dynamic update of user name input box
      pwd: "",
      pwdState: "",
      repwd: "",
      repwdState: "",
      email: "",
      emailState: "",
      phone: "",
      phoneState: "",
      birthday: "",
    };
  },
  methods: {
    // Validation method for encapsulating each field:
    // 1. Verify user name
    checkName() {
      //Event handler: handle the click button verification form
      let reg = /^[a-zA-Z0-9 one-A]{2,6}$/;
      if (reg.test(this.name)) {
        this.nameState = "success";
        return true;
      } else {
        this.nameState = "error";
        return false;
      }
    },
    // 2. Verify password
    checkPwd() {
      let reg = /^d{6}$/;
      if (reg.test(this.pwd)) {
        this.pwdState = "success";
        return true;
      } else {
        this.pwdState = "error";
        return false;
      }
    },
    // 3. Repeat the password
    checkrePwd() {
      let reg = /^d{6}$/;
      if (reg.test(this.repwd) && this.pwd == this.repwd) {
        this.repwdState = "success";
        return true;
      } else {
        this.repwdState = "error";
        return false;
      }
    },
    // 4. Verify email format
    checkEmail() {
      let reg = /^([a-zA-Z]|[0-9])(w|-)+@[a-zA-Z0-9]+.([a-zA-Z]{2,4})$/;
      if (reg.test(this.email)) {
        this.emailState = "success";
        return true;
      } else {
        this.emailState = "error";
        return false;
      }
    },
    // 5. Verify mobile phone number
    checkPhone() {
      let reg = /^1[3|5|7|8][0-9]d{8}$/;
      if (reg.test(this.phone)) {
        this.phoneState = "success";
        return true;
      } else {
        this.phoneState = "error";
        return false;
      }
    },

    checkForm() {
      // After clicking the registration button, this method is called to verify that the user name, password, and two passwords are all correct, and the correct axios request is sent.
      if (this.checkName() && this.checkPwd() && this.checkrePwd()) {
        console.log(`The verification is successful and the registration business is executed......`);
        // Send a registration (post) request
        this.axios
          .post("/register", `username=${this.name}&password=${this.pwd}`)
          .then((result) => {
            console.log(result);
            if (result.data.code == 200) {
              // The pop-up window indicates that the registration is successful
              this.$toast({
                message: "login was successful",
                position: "bottom",
                duration: 3000,
              });
              // After successful registration, directly jump to the login page
              this.$router.push("/login");
            } else if (result.data.code == 201) {
              this.$toast({
                message: "User already exists, please register again",
                position: "bottom",
                duration: 3000,
              });
            }
          });
      }
    },
  },
};
</script>

2. Effect of registration page

3. Relevant codes of login page

Project folder - > login vue

<template>
<!-- Login page -->
  <div class="log">
    <span class="login">Please login</span>
    <span class="reg">
      <router-link to="/register">Register first</router-link>
    </span>
    <!-- mint ui Form components for -->
    <mt-field
      type="text"
      label="user name"
      placeholder="enter one user name"
      v-model="name"
      :state="nameState"
      @blur.native.capture="checkName"></mt-field>
    <mt-field
      type="password"
      label="password"
      placeholder="Please input a password"
      v-model="pwd"
      :state="pwdState"
      @blur.native.capture="checkPwd"></mt-field>
    <hr style="width: 85%" />
    <mt-button class="btn" type="primary" size="large" @click="checkForm">Sign in</mt-button>
  </div>
</template>

<style scoped>
.log .reg {
  font-size: 18px;
}
.log .login {
  font-size: 24px;
  font-family: "Regular script";
  font-weight: 700;
  margin-left: 5px;
  margin-right: 210px;
  line-height: 80px;
}
.log {
  margin-top: 20%;
}
.log .btn {
  background-color: #d86931;
  width: 190px;
  border-radius: 0;
  border: 0;
  margin: auto;
}
.log .btn1 {
  background-color: white;
  border: 2px solid #d86931;
  color: #d86931;
  width: 190px;
  margin: auto;
  margin-top: 30px;
}
</style>>

<script>
export default {
  namespaced: true,
  data() {
    return {
      name: "", //Bidirectional data binding user name input box
      nameState: "", //Handle the dynamic update of user name input box
      pwd: "",
      pwdState: "",
    };
  },
  methods: {
    // Packaging verification method:
    // 1. Verify user name
    checkName() {
      //Event handler: handle the click button verification form
      let reg = /^[a-zA-Z0-9 one-A]{2,6}$/; //2-6 digit numbers, letters and Chinese characters
      if (reg.test(this.name)) {
        this.nameState = "success";
        return true;
      } else {
        this.nameState = "error";
        return false;
      }
    },
    // 2. Verify password
    checkPwd() {
      let reg = /^d{6}$/;
      if (reg.test(this.pwd)) {
        this.pwdState = "success";
        return true;
      } else {
        this.pwdState = "error";
        return false;
      }
    },

    checkForm() {
      // After clicking the login button, this method is called, and the user name and password are verified.
      if (this.checkName() && this.checkPwd()) {
        // Send a login (post) request
        this.axios
          .post("/login", `username=${this.name}&password=${this.pwd}`)
          .then((result) => {
            console.log(result);
            if (result.data.code == 200) {
              // Pop up prompt login successful
              this.$toast({
                message: `Welcome ${this.name}`,
                position: "bottom",
                duration: 3000,
              });
              // Modify user login status in vuex
              this.$store.commit("loginok", this.name);
              // Save islogin and username into sessionStorage
              sessionStorage.setItem("islogin", true);
              sessionStorage.setItem("username", this.name);
              // After successful login, jump to the home page directly
              this.$router.push("/club");
            } else {
              this.$toast({
                message: "Login failed, please check your user name and password",
                position: "bottom",
                duration: 3000,
              });
            }
          });
      }
    },
  },
};
</script>

4. Landing page effect

4, Registration login demo

Enter user information as required.

After successful registration, a pop-up window will appear and jump to the login page. Log in:

Login succeeded.

5, Project file structure

Because the login registration business needs to use the interface and call the database, two folders are required. One is the project folder as the front end; One is the server folder, which serves as the back-end, and both folders need to download node_modules package and start it separately;

The loading of each module, the creation of connection pool and the interface are written in the app under the server JS file. When starting, use the command node app js;

The front-end page is normally written in your project folder. When starting, use the command npm run serve;

Keywords: Front-end Database MySQL html

Added by medar on Wed, 09 Mar 2022 07:15:08 +0200