Vue+Node+MySQL Realizes Front-end and Back-end Separation Development

Time:2019-8-1

Preface

  • This demo is the MVVM development model, and I have also written a complete system demo that combines front-end and back-end development.
  • The Vue project was created using vue-cil3.
  • Projects created using vue-cil2 can also be implemented, except for a slight difference when configuring proxy servers. These two versions are distinguished later.
  • Navicat is used for database operations.

Database Configuration

  1. Create a new MySQL connection (parameters can be configured by themselves, which will be used later)

  2. New database

  3. New Data Table

Node Server

The catalogue structure is as follows:

Vue+Node+MySQL Realizes Front-end and Back-end Separation Development

  1. New folder server
  2. Initialization

    • Open the command window under the server folder
    • Enter the command linenpm init -y

  3. Utls/DBHelper.js – > has MySQL connection configuration, corresponding to the above

    // Database Connection Assistant
    const mysql = require('mysql');
    
    class DBHelper{
        // Get the database connection
        getConn(){
            let conn = mysql.createConnection({
                // Database Connection Configuration
                host:'127.0.0.1',
                port:'3306', 
                user:'root',
                password:'',
                Database:'test'//database name
            });
            conn.connect();
            return conn;
        }
    }
    
    module.exports = DBHelper;
  4. SqlMap.js–> SQL statement for API call

    // SQL statement
    var sqlMap = {
        user: {
            // Adding users
            add: 'insert into user(name, age) values (?, ?)',
            // Query Users
            select: 'select * from user where name like "%"?"%"'
        }
    }
    
    module.exports = sqlMap;
  5. API / userApi. JS – > User API

    const express = require('express');
    const router = express.Router();
    
    const DBHelper = require('../utils/DBHelper');
    const sql = require('../sqlMap');
    
    // Adding users
    router.post('/addUser', (req, res) => {
        let sqlStr = sql.user.add;
        let params = req.body;
        let conn = new DBHelper().getConn();
        conn.query(sqlStr, [params.name, params.age], (err, result) => {
            if (err) {
                res.json(err);
            } else {
                res.json(result);
            }
        });
        conn.end();
    });
    
    // Query Users
    router.post('/selectUser', (req, res) => {
        let sqlStr = sql.user.select;
        let params = req.body;
        let conn = new DBHelper().getConn();
        conn.query(sqlStr, [params.name], (err, result) => {
            if (err) {
                res.json(err);
            } else {
                res.json(result)
            }
        });
        conn.end();
    });
    
    module.exports = router;
  6. Index.js – > Server Entry File

    // node back-end server
    const http = require('http');
    const badyParser = require('body-parser');
    const express = require('express');
    const userApi = require('./api/userApi');
    
    let app = express();
    let server = http.createServer(app);
    
    app.use(badyParser.json());
    app.use(badyParser.urlencoded({
        extended: false
    }));
    
    // back-end API routing
    app.use('/api/user', userApi);
    
    // Start listening
    server.listen(8888, () => {
        console.log(' success!! port:8888')
    })
  7. Use the command linenpm install -S mysqlInstall the MySQL package and use the command linenode index.jsStart the service.

Vue front-end file

  1. Use the command linevue create vue-node-demoCreate a project, vue-cil2 creates a project reference to this
  2. This is not a formal project, it’s directly in theHelloWorld.vueEditing:

    <template>
      <div class="hello">
        <form action="">
          Name: <input type="text" name="username" v-model="userName"><br>
          Age: <input type="text" name="age" v-model="age">br>
          <button type="button"@click="addUser"> submit information </button>
        </form>
        <form action="">
          <input type= "text" v-model= "keywords" placeholder= "input name query">
          <button type="button"@click="selectUser">query</button>
        </form>
      </div>
    </template>
    
    <script>
    import axios from 'axios'
    
    export default {
      name: 'HelloWorld',
      props: {
        msg: String
      },
      data(){
        return{
          userName:'',
          age:'',
          keywords:''
        }
      },
      methods:{
        addUser(){ //
          let name = this.userName;
          let age = this.age;
          axios.post('/api/user/addUser',{
            name,age
          }).then(res=>{
            Alert ('information added successfully');
          }).catch(err=>{
            console.log(err)
          })
        },
        selectUser(){
          let name = this.keywords;
          axios.post('api/user/selectUser',{
            name
          }).then(res=>{
            let data = res.data[0];
            this.userName = data.name;
            this.age = data.age
          }).catch(err=>{
            console.log(err)
          })
        }
      }
    }
    </script>

Setting up proxy to handle cross-domain

Failure to set up will result in 404 errors.

Because direct access to port 8888 is not accessible, proxy servers need to be set up here.

Project settings created by vue-cli3

Create new files in the root directoryvue.config.js

module.exports = {
    devServer: {
        Proxy: {// Setting up Agents
            '/api': {
                Target:'http://127.0.0.1:8888', //request target server interface
                ChangeOrigin: true, // creates a virtual server locally, then sends the requested data and receives the requested data at the same time, so that there is no cross-domain problem in data interaction between the server and the server.
                PathRewrite: {//rewrite request
                    '^/api':'/api'// Replace the request address in target, that is to say, write directly as / API when requesting http://127.0.0.1:8888/XXXXX.
                }
            }
        }
    }
}

Project settings created by vue-cli2

// Path: config/index.js
proxyTable: {
    '/api': {
        target: 'http://127.0.0.1:8888',
        changeOrigin: true,
        pathRewrite: {
            '^/api': '/api'
        }
    }
}

Demonstration

Take a look at the effect (for demonstration, without styling):

  • Command line inputnpm run serveRunning development environment, project input created by vue-cil2npm run dev
  • Fill in the information, click the submit button, refresh the database, you can see that the data has been written to the database.

  • Enter keywords, and the query results are successfully rendered to the above form. (Provided there is this data in the database)

Last

  • Demo has uploaded Github
  • Vue project actual combat, cat’s eye mobile end, from 0 to build the complete project