vue create a server connection mysql

Installation node

node official website address: https://nodejs.org/en/

To see if the installation was successful

1 node - v
 2 npm - v
 3 cnpm -v

Installation cnpm

Use npm install dependencies module may be slow, it is recommended replaced [cnpm]

. 1 <-! -G indicates global installation ->
 2 NPM CNPM --registry the install -g = HTTP: // registry.npm.taobao.org

Vue-cli install scaffolding tool

. 1 CNPM the install -g @ VUE / CLI Cli # mounted Vue 
 2 CNPM the install -g @ VUE / CLI-installed after the init # can also be used vue init command

Create a project folder into the project directory execute:

1 <-! My-Project is the project name ->
 2 VUE the init WebPACK My-Project

Inside into the project, installing vue-resource-dependent

1 cd my-project
2 cnpm install vue-resource
3 cnpm install express mysql body-parser

 

Adding server directory server

Create a server folder in the project root folder. Then create the following three files inside; db.js index.js sqlMap.js

And api directories, api built inside a file userApi.js

db.js-- arranged to add mysql

According to the mysql IP, port, user name, password, database name to amend its own

1  // database connection configuration 
2 module.exports = {
 . 3      MySQL: {
 . 4          Host: ' localhost ' ,
 . 5          User: ' the root ' , #mysql user name
 . 6          password: '' , # password
 . 7          Database: ' Movie ' , # database name Note: the database should be established in advance, in the end the step
 8          port: ' 3306 '                      # recommend using the default port 3306.
 9      }
 10 }

index.js - Express server entry file

 1 // node 后端服务器
 2 
 3 const userApi = require('./api/userApi');
 4 const fs = require('fs');
 5 const path = require('path');
 6 const bodyParser = require('body-parser');
 7 const express = require('express');
 8 const app = express();
 9 
10 app.use(bodyParser.json());
. 11 app.use (bodyParser.urlencoded ({Extended: to false }));
 12 is  
13 is  // rear api route 
14 app.use ( ' / api / User ' , userApi);
 15  
16  // listening port 
. 17 app.listen ( 3000 );
 18 is the console.log ( ' Success the listen AT Port: 3000 ...... ' );

sqlMap.js - SQL statement mapping files for API calls

1 // sql语句
2 var sqlMap = {
3     // 用户
4     user: {
5         add: 'insert into user(id, name, age) values (0, ?, ?)'
6     }
7 }
8     
9 module.exports = sqlMap;

api / userApi.js - API test sample

 1 var models = require('../db');
 2 var express = require('express');
 3 var router = express.Router();
 4 var mysql = require('mysql');
 5 var $sql = require('../sqlMap');
 6 
 7 // 连接数据库
 8 var conn = mysql.createConnection(models.mysql);
 9 
10 conn.connect();
11 var= jsonWrite function (RES, RET) {
 12 is      IF ( typeof RET === ' undefined ' ) {
 13 is          res.json ({
 14              code: ' . 1 ' ,
 15              MSG: ' operation failed ' 
16          });
 . 17      } the else {
 18 is          res.json (RET);
 . 19      }
 20 is  };
 21 is      
22 is  // increase user interface 
23 is router.post ( ' / the addUser ', (req, res) => {
24     var sql = $sql.user.add;    
25     var params = req.body;    
26     console.log(params);
27     conn.query(sql, [params.username, params.age], function(err, result) {    
28         if (err) {       
29             console.log(err);
30         }        
31         if (result) {
32             jsonWrite(res, result);
33         }
34     })
35 });
36 module.exports = router;

 

 Vue-resource introduced in the main.js

 1 // The Vue build version to load with the `import` command
 2 // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
 3 import Vue from 'vue'
 4 import App from './App'
 5 import router from './router'
 6 
 7 import VueRouter from 'vue-router'
 8 import VueResource from 'vue-resource'
 9 
10 /*NO-disable-new new eslint * / 
. 11  new new Vue ({
 12 is    EL: ' #app ' ,
 13 is    Router,
 14    Template: ' <the App /> ' ,
 15    Components: the App} {
 16  })
 . 17  
18 is  // required here after use, this. $ http.get or this. $ http.post only be 
19  Vue.use (VueRouter)
 20 Vue.use (VueResource)

Cross-domain and proxy settings

index.js config file directory vue-cli proxyTable of a parameter used to set the address mapping table may be added to the configuration (dev) the development of

 1 dev: {
 2     env: require('./dev.env'),
 3     port: 8080,
 4     autoOpenBrowser: true,
 5     assetsSubDirectory: 'static',
 6     assetsPublicPath: '/',
 7     proxyTable: {        
 8         '/api': {
 9             target: 'http://localhost:3000/api/',
10             changeOrigin: true,
 11              pathRewrite: {                
 12                  ' ^ / The api ' : '' 
13              }
 14          }
 15      },
 16      cssSourceMap: false the 
17    }
 18 }

Project configuration is completed

At this point in the server folder under execution node index  to see success listen at port: 3000 ...... that is the server started successfully.
In the run npm run dev project my-project directory, see Your application is running here: http: // localhost: 8080, can enter the browser and enter http: // localhost: 8080 View page
 
 

Write vue

HelloWorld.vue

 1 <template>
 2   <div class="hello">
 3     <h1>{{ msg }}</h1>
 4     <form>
 5       <input type="text" name="username" v-model="userName"> <br>
 6       <input type="text" name="age" v-model="age"> <br>
 7       <a href="javascript:;" @click="addUser">提交</a>
 8     </form>
 9   </div>
10 </template>
11 <script>
12 export default {
13   name: 'hello',
14   data () {
15     return {
16       msg: 'Welcome to Your Vue.js App',
17       userName: '',
18       age: ''
19     }
20   },
21   methods: {
22     addUser() {
23       var name = this.userName;
24       var age = this.age;
25       this.$http.post('/api/user/addUser', {
26         username: name,
27         age: age
28       },{}).then((response) => {
29         console.log(response);
30       })
31     }
32   }
33 }
34 </script>

Refresh your browser, you can add data to the database

 

Note: The database is set up in advance

cmd to run code
1 MySQL -u root - the p-# When prompted, enter the database password
 2  the Create Database Movie; # delete database with Movie Database drop;
 3  Show Databases;
 4  use Movie
 5  Show the Tables;
 6  # New Table
 7  the CREATE TABLE the User; (                         
 8      movie_id CHAR ( 20 is ) the DEFAULT ' 0000 ' ,
 . 9      movie_url CHAR ( 20 is ) the DEFAULT '' );
 10  # truncate table with the drop table drop table table name table;
 . 11  
12 is the INSERT the INTO User (movie_id, movie_url) the VALUES ( '12345 ' , ' 34567 ' ); inserting data into a table #

 

 

Guess you like

Origin www.cnblogs.com/koiyun/p/12367612.html