In the first two months, I have been learning Vue and Node.js, but I didn’t really start the project. I happened to be required by the company to build an independent operating system for login and registration, and I took this opportunity to learn and consolidate what I have learned before. Vue is used in the front end, Express is used in the back end to provide data interface, and MySql is used in the database. The realization of the database to change the operation.

The demo request

Complete a set of independent operation of the front-end system, including registration, login, personal center three functional modules.

  • 1. Development technology and development framework are not limited.
  • 2. The user includes the following information: user name, account name, password, duplicate password, email address, mobile phone, ID card, date of birth, gender
  • 3. During registration, non-null verification and format verification should be performed on user information, and password consistency verification should be performed twice
  • 4. A verification code is required for login and verification is required. If verification fails, the verification code is automatically updated and the verification code is manually updated
  • 5. You can modify your personal information, log out, and change your password after successfully logging in to the personal Center
  • Additional: Personal center provides avatar and modify avatar function

The preparatory work

node.js

mysql

git

express

element-UI

The directory structure

Let’s start with the directory structure of the project

Vue – CLI creates a Webpack-based VUE login registration system project

NPM install -g vue-cli

Install dependencies by adding the corresponding version to package.json and then executing NPM install

  "dependencies": {
    "axios": "^ 0.15.3"."babel-polyfill": "^ 6.23.0"."body-parser": "^ 1.18.2"."element-ui": "1.3.1"."mysql": "^ 2.15.0"."vue": "^" 2.3.2."vue-core-image-upload": 2.1.11 ""."vue-datasource": "1.0.9"."vue-router": "^ 2.3.1." ",},Copy the code

Server Configuration

Create a Service folder under the project root folder. Then create the following four files: db/db.js — to add MySQL configuration

module.exports = {
    mysql: {
        host: 'localhost',
        user: 'root',
        password: ' ',
        port: '3306',
        database: 'login'}}Copy the code

App.js — Express server entry file

const userApi = require('./api/userApi');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded())

app.use('/api/user', userApi);

app.listen(3000);
console.log('success listen at port: 3000')
Copy the code

Db/sqlmap. js—-SQL statement mapping file, which is mainly used to change and check the database.

var sqlMap = {
    user: {
        add: 'insert into user (username, account, password, repeatPass, email, phone, card, birth, sex) values (? ,? ,? ,? ,? ,? ,? ,? ,?) ',
        select_name: 'select * from user', 
        update_user: 'update user set'
    }
}

module.exports = sqlMap;
Copy the code

The query statement has been problematic

select_name: 'select * from user where username = ? ',

Where username =? See below for details. If you have a better solution, please give me your advice.

router.post('/login', (req, res) => {
    var sql_name = $sql.user.select_name;
    // var sql_password = $sql.user.select_password;
    var params = req.body;
    console.log(params);
    if (params.name) {
        sql_name += "where username ='"+ params.name +"'";
    }
    var keywords = JSON.parse(Object.keys(params)[0]);
    conn.query(sql_name, params.name, function(err, result) {
        if (err) {
            console.log(err);
        }
        // console.log(result);
        if (result[0] === undefined) {
            res.send('1'// Select * from user where username = 1;else {
            var resultArray = result[0];
            console.log(resultArray.password);
           // console.log(keywords);
            if(resultArray.password === keywords.password) {
                jsonWrite(res, result);
            } else {
                res.send('0')   //username
            }
        }
    })
});
Copy the code

API/userapi.js —- Test API examples

var models = require('.. /db/db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('.. /db/sqlMap');

var conn = mysql.createConnection(models.mysql);

conn.connect();

var jsonWrite = function(res, ret) {
    if(typeof ret === 'undefined') {
        res.send('err');
    } else {
        console.log(ret);
        res.send(ret);
    }
}

var dateStr = function(str) {
    returnNew Date (STR. Slice (0, 7)); } // Add a user interface router.post('/addUser', (req, res) => {
    var sql = $sql.user.add;
    var params = req.body;
    console.log(params);
    console.log(params.birth);
    conn.query(sql, [params.name, params.account, params.pass, params.checkPass,
                    params.email, params.phone, params.card, dateStr(params.birth), params.sex], function(err, result) {
        if (err) {
            console.log(err);
        }
        if(result) { jsonWrite(res, result); }})}); Router.post ('/login', (req, res) => {
    var sql_name = $sql.user.select_name;
    // var sql_password = $sql.user.select_password;
    var params = req.body;
    console.log(params);
    if (params.name) {
        sql_name += "where username ='"+ params.name +"'";
    }
    var keywords = JSON.parse(Object.keys(params)[0]);
    conn.query(sql_name, params.name, function(err, result) {
        if (err) {
            console.log(err);
        }
        // console.log(result);
        if (result[0] === undefined) {
            res.send('1'// Select * from user where username = 1;else {
            var resultArray = result[0];
            console.log(resultArray.password);
           // console.log(keywords);
            if(resultArray.password === keywords.password) {
                jsonWrite(res, result);
            } else {
                res.send('0') //username } } }) }); Router.get ('/getUser', (req, res) => {
    var sql_name = $sql.user.select_name;
    // var sql_password = $sql.user.select_password;
    var params = req.body;
    console.log(params);
    if (params.name) {
        sql_name += "where username ='"+ params.name +"'";
    }
    conn.query(sql_name, params.name, function(err, result) {
        if (err) {
            console.log(err);
        }
        // console.log(result);
        if (result[0] === undefined) {
            res.send('1'// Select * from user where username = 1;else{ jsonWrite(res, result); }})}); // Update user information router.post('/updateUser', (req, res) => {
    var sql_update = $sql.user.update_user;
    var params = req.body;
    console.log(params);
    if (params.id) {
        sql_update  += " email = '" + params.email +
                        "',phone = '" + params.phone +
                        "',card = '" + params.card +
                        "',birth = '" + params.birth +
                        "',sex = '" + params.sex +
                        "' where id ='"+ params.id + "'";
    }    
    conn.query(sql_update, params.id, function(err, result) {
        if (err) {
            console.log(err);
        }
        console.log(result);
        if (result.affectedRows === undefined) {
            res.send('Update failed, please contact administrator'// Select * from user where username = 1;else {
            res.send('ok'); }})}); // Change the password router.post('/modifyPassword', (req, res) => {
    var sql_modify = $sql.user.update_user;
    var params = req.body;
    console.log(params);
    if (params.id) {
        sql_modify +=  " password = '" + params.pass +
                        "',repeatPass = '" + params.checkPass +
                        "' where id ='"+ params.id + "'";
    }
    conn.query(sql_modify, params.id, function(err, result) {
        if (err) {
            console.log(err);
        }
        // console.log(result);
        if (result.affectedRows === undefined) {
            res.send('Failed to change password, please contact administrator'// Select * from user where username = 1;else {
            res.send('ok'); }})}); module.exports = router;Copy the code

Success Listen at port:3000…… That is, the server is successfully started.

Vue login component

This section describes how to login to login.vue

<template>
    <div class="login-wrap">
        <div class="ms-title"> Log in to the management system </div> <div class="ms-login">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
                <div v-if="errorInfo">
                    <span>{{errInfo}}</span>
                </div>
                <el-form-item prop="name">
                    <el-input v-model="ruleForm.name" placeholder="Account" ></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password" placeholder="Password" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')"></el-input>
                </el-form-item>
                <el-form-item  prop="validate">
                    <el-input v-model="ruleForm.validate" class="validate-code" placeholder="Verification code" ></el-input>
                    <div class="code" @click="refreshCode">
                        <s-identify :identifyCode="identifyCode"></s-identify>
                    </div>
                </el-form-item>
                <div class="login-btn">
                    <el-button type="primary" @click="submitForm('ruleForm')"<p style= "max-width: 100%; clear: both; min-height: 1em"font-size:14px; line-height:30px; color:#999; cursor: pointer; float:right;" @click="handleCommand()"> register < / p > < / el - form > < / div > < / div > < / template > < script >export default {
        name: 'login'.data() {
            return {
                identifyCodes: "1234567890",
                identifyCode: "",
                errorInfo : false,
                ruleForm: {
                    name: ' ',
                    password: ' ',
                    validate: ' '                    
                },
                rules: {
                    name: [
                        { required: true, message: 'Please enter a user name', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: 'Please enter your password', trigger: 'blur' }
                    ],
                    validate: [
                        { required: true, message: 'Please enter the verification code', trigger: 'blur'}]}}},mounted() {
            this.identifyCode = "";
            this.makeCode(this.identifyCodes, 4);
        },
        methods: {
            submitForm(formName) {
                const self = this;
                self.$refs[formName].validate((valid) => {
                    if (valid) {
                        localStorage.setItem('ms_username',self.ruleForm.name);
                        localStorage.setItem('ms_user',JSON.stringify(self.ruleForm));
                        console.log(JSON.stringify(self.ruleForm));                        
                        self.$http.post('/api/user/login',JSON.stringify(self.ruleForm))
                        .then((response) => {
                            console.log(response);
                            if (response.data == -1) {
                                self.errorInfo = true;
                                self.errInfo = 'This user does not exist';
                                console.log('This user does not exist')}else if (response.data == 0) {
                                console.log('Password error')
                                self.errorInfo = true;
                                self.errInfo = 'Password error';
                            } else if (response.status == 200) {
                                self.$router.push('/readme'); } }).then((error) => { console.log(error); })}else {
                        console.log('error submit!! ');
                        return false; }}); },handleCommand() {
                this.$router.push('/register');
            },
            randomNum(min, max) {
                return Math.floor(Math.random() * (max - min) + min);
            },
            refreshCode() {
                this.identifyCode = "";
                this.makeCode(this.identifyCodes, 4);
            },
            makeCode(o, l) {
                for (let i = 0; i < l; i++) {
                    this.identifyCode += this.identifyCodes[
                    this.randomNum(0, this.identifyCodes.length)
                    ];
                }
                console.log(this.identifyCode);
            }
        }
    }
</script>

<style scoped>
    .login-wrap{
        position: relative;
        width:100%;
        height:100%;
    }
    .ms-title{
        position: absolute;
        top:50%;
        width:100%;
        margin-top: -230px;
        text-align: center;
        font-size:30px;
        color: #fff;

    }
    .ms-login{
        position: absolute;
        left:50%;
        top:50%;
        width:300px;
        height:240px;
        margin:-150px 0 0 -190px;
        padding:40px;
        border-radius: 5px;
        background: #fff;
    }
    .ms-login span {
        color: red;
    }
    .login-btn{
        text-align: center;
    }
    .login-btn button{
        width:100%;
        height:36px;
    }
    .code {
        width: 112px;
        height: 35px;
        border: 1px solid #ccc;
        float: right;
        border-radius: 2px;
    }
    .validate-code {
        width: 136px;
        float: left;
    }
</style>
Copy the code

Set up proxy and cross domain

After executing the above steps, execute NPM run dev in the root directory, enter a set of data, and click Save. You will find an error: vue-resource.common.js?e289:1071 POST http://localhost:8082/api/user/login 404 (Not Found). This is because you cannot access port 8082 directly, so you need to set the proxy forwarding mapping.

Vue-cli config file has a proxyTable parameter to set the address mapping table, which can be added to development-time configuration (dev)

dev: {
    // ...
    proxyTable: {
        '/api': {
            target: 'http://127.0.0.1:3000/api/',
            changeOrigin: true,
            pathRewrite: {
                '^/api': ' '}}}, //... }Copy the code

Namely request/API is http://127.0.0.1:3000/api/ (IP to write here, don’t write localhost), changeOrigin parameter receiving a Boolean value, if it is true, so there will be no cross domain problem.

In the project, it is required to prevent multiple submissions, which is actually anti-shake operation: please move step throttling and anti-shake for details

Project running

// Local development // To enable the front-end service, visit http://localhost:8082 NPM run dev // to enable the back-end servicecd service
node app
Copy the code

After a whole day and an afternoon, I finally got through the adjustment. I met a lot of problems in the database, but I finally solved them after continuous attempts.

rendering

Improper source code, also please correct, welcome star

Reference below vue-manage-system, Island Heart Hey, Luo Kun