vue+node+mySql to separate front and back end

Posted by Concat on Wed, 01 Apr 2020 13:05:01 +0200

Environment building

Install node first:

http://nodejs.cn/download/
Download and install it directly! The new version does not need to manually configure the environment. After installation, open cmd and input node-v and npm-v to check whether the installation is successful.

The second step is to install vue:

Type npm install vue directly on the command line. Enter the directory where you want to create the project;
//Installation of scaffolding
npm install –global vue-cli
//Install webpack dependencies
vue init webpack my-project
//Enter into the project
cd my-project
npm install
//Running the vue project
npm run dev

Step 3: install node express:

Under my project (cmd input)
: npm install express

The fourth step is to install xammp and navicat:

This will not be introduced! Just run mysql after the installation. Then use navicat to build the database.

Get to the point!! ——————–

Write a simple login function

Look at the effect first!!
Take a look at the vue code (local)

//You need to use Vue resource here or this.$http.post will report an error! This recommendation is written by a God in detail
> http://blog.csdn.net/wcslb/article/details/55057010
<template>  
    <div class="Login">
        <a href="javascript:void(0)" v-on:click = "loginbtn">Deng &nbsp;  &nbsp;   record&nbsp;&nbsp;</a>
        <a href="javascript:void(0)" v-on:click = "regbtn">|&nbsp;&nbsp;Register new users</a>
        <form @submit.prevent="submit_login" method="post" id="login_in">
            <input type="text" name="" id="" value="" placeholder="enter one user name" v-model="loginData.username"/><label for=""></label>
            <input type="password" name="" placeholder="Please input a password" v-model="loginData.psw"/>
            <input type="submit" class="sub_btn" value="Deng    record"/>
        </form>
        <form @submit.prevent="submit_req" method="post" id="login_registered">
            <input type="text" name="" id="" value="" placeholder="User name" v-model="regData.username"/><label for=""></label>
            <input type="password" name="" placeholder="Password" v-model="regData.psw"/>
            <input type="password" name="" placeholder="Confirm password" v-model="regData.tpsw"/>
            <input type="submit" class="sub_btn" value="Immediate registration"/>
        </form>
    </div>
</template>
<script type="text/javascript">
export default{
    data() {
        return{
            loginData: {
            },
            regData: {      
            }
        } 
    },
    methods: {
        loginbtn: function(){
            document.getElementById("login_in").style.display="block";
        },
        regbtn: function(){
            document.getElementById("login_in").style.display="none";
        },
        submit_login: function(){
            console.log(this.loginData);
            var url="/api/login";
            this.$http.post(url,{
                username: this.loginData.username,
                userpsw: this.loginData.psw
            },{}).then(function(data){
                console.log("Ask for attack! ",data.body);
                var content=data.body;
                if (content.length != 0) {
                    alert("Login succeeded!");
                }else{
                    alert("Account password error!");
                }
            },function(response){
                console.log(response);
            })
        },
        submit_req: function(){
            var reg_name =  this.regData.username;
            var reg_psw = this.regData.psw;
            if(reg_psw !== this.regData.tpsw){
                alert("The password entered twice is incorrect!");
                this.regData.username = "";
                this.regData.psw = "";
                this.regData.tpsw = "";
            }else{
                var url="/api/addUser";


                this.$http.post(url,{
                    username: this.regData.username,
                    userpsw: this.regData.psw
                },{}).then(function(data){
                    console.log("Register for attack! ",data.body);
                    if (data.body.affectedRows >0) {
                        alert("Register to attack!");
                        document.getElementById("login_in").style.display="block";
                    }
                },function(response){
                    console.log(response);
                })
            }
        }
    }
}
</script>
<style scoped>
    .Login{
        width: 70%;
        height: 70%;
        background: rgba(255,255,255,0.8);
        border: 5px solid #E23A6E;
        margin: 0 auto;
        margin-top: 5%;
    }
    .Login a{
        text-decoration: none;
        color: #E23A6E;
    }
    .Login form{
        width: 100%;
        height: 100%;
    }
    .Login input{
        width: 50%;
        height: 40px;
        margin-top: 30px;
        border: 1px solid #E23A6E;
        border-radius: 20px;
        outline: none;
        font-family: "arial rounded mt bold";
        padding-left: 10px;
        font-size: 18px;
    }
    .sub_btn{
        cursor: pointer;
        background: none;
        color: #E23A6E;
    }
    .sub_btn:hover{
        background: #E23A6E;
        color: #FFFFFF;
    }
</style>

New server directory

Create the servser folder node file directly in the vue project and put it into the project.
Finally, npm run build will generate the dist folder! The file in the folder is the last page.

node code

Set up the service first

// node backend server

const userApi = require('./api');
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({extended: false}));
// Access the data under the specified compiled dist file after the service is started
app.use(express.static(path.resolve(__dirname, '../dist')))
app.get('*', function(req, res) {
    const html = fs.readFileSync(path.resolve(__dirname, '../dist/index.html'), 'utf-8')
    res.send(html)
})
// Back end api routing
app.use('/api', userApi);
// Monitor port
app.listen(8088);
console.log('success listen at port:8088......');

Establish api interface

var models = require('./db');//Database link information
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('./sqlfun');//sql Sentence

// Connect to database
var conn = mysql.createConnection(models.mysql);

conn.connect();
var jsonWrite = function(res, ret) {
    if(typeof ret === 'undefined') {
        res.json({
            code: '1',
            msg: 'operation failed'
        });
    } else {
        res.json(ret);
    }
};

// Login user interface
router.post('/login', (req, res) => {
    var sql = $sql.user.login;    
    var params = req.body; 
    console.log("sql",sql);
    console.log("params",params);
    conn.query(sql, [params.username], function(err, result) {    
        if (err) {       
            console.log(err);
        }        
        if (result) {
            jsonWrite(res, result);
            for(var i = 0; i < result.length; i++){
                console.log("Please come back!",result[i])
                console.log("Request results!",typeof result[i],result[i].userpsw);
                if (result[i].userpsw == params.userpsw) {
                    res.send("Come back!");
                }
            }
            res.end('is over');
        }
    })
});
// Add user interface
router.post('/addUser', (req, res) => {
    var sql = $sql.user.add;    
    var params = req.body; 
    console.log("sql",sql);
    console.log("params",params);
    conn.query(sql, [params.username,params.userpsw], function(err, result) {    
        if (err) {       
            console.log(err);
        }        
        if (result) {
            jsonWrite(res, result);
            for(var i = 0; i < result.length; i++){
                console.log("Please come back!",result[i])
                console.log("Request results!",typeof result[i],result[i].userpsw);
                if (result[i].userpsw == params.userpsw) {
                    res.send("Come back!");
                }
            }
            res.end('is over');
        }
    })
});
module.exports = router;

data base

// Database connection configuration
module.exports = {
    mysql: {
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'qyk',
        port: '3306'
    }
}
// sql statement
var sqlMap = {
    // user
    user: {
        login: 'SELECT userpsw FROM admin WHERE username = ?;',
        add: 'insert into admin(username, userpsw) values ( ?, ?);'
    }
}

module.exports = sqlMap;

vue routing management and cross domain management

Add the following code to dev: in the index.js file under the config folder.

    proxyTable: {        
        '/api': {
            target: 'http://localhost:8088/api/',
            changeOrigin: true,
            pathRewrite: {                
                '^/api': ''
            }
        }
    }

Run localhost directly: 8088

ok.

Topics: SQL Vue npm MySQL