Before setting up the project, install the Node environment and mysql database.

1. Create a VUE project using vuE-CLI scaffolding

A. Global install NPM install -g vue-cli

B. Initialize the project vue init webPack MyExpress

c.npm install

d.npm run dev

2. Add the Express back-end directory to the vue project

A. Create a server folder in the following directory

  

B. In the server folder, create API folders, db.js, index.js, and sqlmap.js. (API file storage API interface path and method, db.js configuration database, index.js configuration back-end port and API routing)

  

3. Configure the db.js database

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

4.index.js

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.urlencoded({extended: true}));
app.use(bodyParser.json());
// Back-end API routing
app.use('/api/user', userApi);

// Listen on the port
app.listen(3000);
console.log('success listen at port:3000...... ');

Copy the code

5.sqlMap.js

var sqlMap = {
  / / user
  user: {
    add: 'insert into user(name,age) values(? ,?) '}}module.exports = sqlMap;
Copy the code

6. The API to write

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



// Connect to the 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); }};// Add a user interface
router.post('/addUser'.(req, res) = > {
  let sql = $sql.user.add;
  let params = req.body;
  console.log(params);
  conn.query(sql, [params.name, params.age], function(err, result) {
    if (err) {
      console.log("Add failed"+err);
    }
    if(result) { jsonWrite(res, result); }})});module.exports = router;
Copy the code

7. Vue page preparation

Test 8.

Note: from: www.cnblogs.com/xufeikko/p/…