Vue connect MySql database

A, vue-cli2

  1. Global Installation

npm install vue-cli -g

 

  1. Local installation project

vue init webpack project name

For example: vue init webpack demo1

 

二、express-generator

1. Global Installation

npm install express-generator -g

2.express --view = ejs project name

For example: express --view = ejs server

3. Install Database

npm install mysql

Three, server deployment steps

Note: The first download mysql, open

1. [installed into the distal root directory server]

[Db 2. Create a folder -> Create sql.js]

var mysql   =  require('mysql')
// Connect to the database
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'miao',
    password: 'miao',
    database: 'myemployees'
})


module.exports = connection;

【3.server->routes->index.js】

var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js')


router.get('/api/userInfo', function(req, res, next) {
   connection.query("select * from departments",function(error,results,fields){
     console.log(results)
     res.json(results)
   })
});


router.get('/api/info', function(req, res, next) {
  res.json(
      [
        {
          name:"小明",
          age:20,
          address: 'Beijing'
        },
        {
          name: "Mandy"
          age:23,
          address: 'Shanghai'
        }
      ]
    );
});


module.exports = route

 

 

 

Fourth, the distal deployment steps vue

Cross-domain need to change agent

[1. The agent: vue front-end catalog -> config-> index.js]

// Agent
    proxy table: {
      '/api': {
        target: 'http: // localhost: 3000', // destination address
        changeOrigin: true, // whether cross-domain default false
        PathRewrite: {// path rewritable
          '^ / Api': '' // here is the cause of the problem, the correct wording should be: '^ / api': '/ api'
        }
      }
    },

[2.] installation axios

cnpm i axios -v
[Main.js global reference]
import axios from 'axios'
. Vue.prototype $ axios = axios // global registration, use the method:. This $ axios

[Quote] 3. Component

 mounted(){
    this.$axios.get('/api/userInfo').then ((res) => {
      console.log(res)
    })
  }

Published 231 original articles · won praise 166 · views 440 000 +

Guess you like

Origin blog.csdn.net/miaozhenzhong/article/details/103872254