1. 程式人生 > >Node+Express+Vue+Element+MySQL簡易實現前後端分離

Node+Express+Vue+Element+MySQL簡易實現前後端分離

原始碼

1、安裝node環境
具體安裝教程請參考http://nodejs.cn/

2、塔建Vue前端專案
使用Vue官網提供的vue-cli腳手架vue-cli命令列工具

# 全域性安裝 vue-cli
$ npm install --global vue-cli
# 建立一個基於 webpack 模板的新專案
$ vue init webpack nevem
# 安裝依賴,走你
$ cd nevem
$ npm install
$ npm run dev

注意:

npm install --global vue-cli

  全域性安裝 vue-cli。

vue init webpack nevem

建立一個基於 webpack 模板的新專案。在這一步時,下圖的這幾個單元測試和程式碼檢驗工具建議填寫no,不然會增加專案的體積和寫程式碼時因為不規範產生一大堆報錯。
在這裡插入圖片描述

cd nevem

安裝vue-resource和element-ui依賴: cd nevem進入前端專案後,找到package.json檔案對應的地方,確保有新增如下程式碼:

"dependencies": {
    "element-ui": "^1.3.2",
    "vue": "^2.2.6",
    "vue-resource": "^1.0.3",
    "vue-router": "^2.3.1"
  },

npm install

安裝所有的依賴,包括上一步驟的elementUI和vue-resource。

執行npm install安裝時間會長一點,所以建議使用淘寶cnpm映象(自行google),公司的網路已牆的請忽略。

npm run dev後頁面自動彈出http://localhost:8080/#/這個頁面,表明基於webpack的vue專案成功建立。
在這裡插入圖片描述

3、引入Element元件
修改src/main.js為如下程式碼,引入element和resource

import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'

Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
  render:h => h(App)
})

修改src/componentsHello.vue檔案為如下程式碼,調整首頁的內容

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>{{el}}</p>
    <form>
        <el-input v-model="name" placeholder="名稱" style="width:200px"></el-input>
        <el-input v-model="price" placeholder="價格" style="width:200px"></el-input>
        <el-button type="primary" @click="addUser">提交</el-button>
    </form>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      name: '',
      price: '',
      el:''
    }
  },
  methods: {
    addUser() {
      var name = this.name;
      var price = this.price;
      this.$http.post('/api/user/addUser', {
        name: name,
        price: price
      },{}).then((response) => {
        console.log(response);
      })
    },
    aaa(){
      this.el="成功引入element";
    }
  }
}
</script>

儲存以上檔案之後,在nevem目錄再次執行npm run dev,頁面變成如下效果,則表示成功引入element元件。
在這裡插入圖片描述

4、安裝Mysql
安裝mysql的形式有很多種,這裡我使用的是WampServer建立一個數據庫,具體如果安裝和使用,依舊自行google。

這裡我新增了一個Database資料庫,名稱為mbvr_live,然後在資料庫裡建立一張表goods並插入了兩條記錄,具體sql程式碼如下:

CREATE TABLE IF NOT EXISTS `goods` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `price` float(10,2) NOT NULL,
  `creat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `goods` (`id`, `name`, `price`, `creat_time`) VALUES
(1, 'apple', 5.00, '2017-05-11 00:22:10'),
(2, 'banner', 5.00, '2017-05-11 01:37:37');

5、安裝Express
在目錄nevem下新建一個檔案service,用於做伺服器。在裡面建立如下4個檔案,結構如下:
在這裡插入圖片描述

db.js,用來配置mysql連線資料:

module.exports = {
    mysql: {
        host: 'localhost',
        user: 'root',
        password: '',
        database:'mbvr_live'
    }
}

app.js,Express伺服器入口檔案:

// node 後端伺服器入口
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.json());
app.use(bodyParser.urlencoded({extended: false}));

//註冊api路由
app.use('/api/user', userApi);

// 監聽埠
app.listen(3000);
console.log('success listen at port:3000......');

sqlMap.js,SQL語句對映檔案,以供api邏輯呼叫:

// sql語句
var sqlMap = {
    // 使用者
    user: {
        add: 'insert into goods(id, name, price) values (0, ?, ?)'
    }
}
module.exports = sqlMap;

userApi.js,測試示例:

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

// 連線資料庫
var conn = mysql.createConnection(models.mysql);

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

// 增加使用者介面
router.post('/addUser', (req, res) => {
    var sql = $sql.user.add;
    var params = req.body;
    console.log(params);
    conn.query(sql, [params.name, params.price], function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            jsonWrite(res, result);
        }
    })
});
// 增加使用者介面
router.get('/addUser', (req, res) => {
     res.send('retrunJson');
});

module.exports = router;

編寫完成之後,就可以在service專案下安裝相關的依賴npm install express mysql body-parser;

此時在service資料夾下執行node app如看到success listen at port:3000,即服務端啟動成功。

6、測試
這時候,返回http://localhost:8080/#/頁面輸入名稱和價格後並提交,發現報http://localhost:8080/api/use… 的404錯誤,這是因為後端8080和前端3000是兩個不同的埠,跨域了。這時候,找到檔案configindex.js,在開發配置dev裡面的地址對映表proxyTable內容為空,這裡修改為:

proxyTable: {
        '/api': {
            target: 'http://127.0.0.1:3000/api/',//不要寫localhost
            changeOrigin: true,//true允許跨域
            pathRewrite: {
                '^/api': ''  //需要rewrite重寫的, 如果在伺服器端做了處理則可以不要這段
            }
        }
    },

原文:https://www.ctolib.com/topics-115998.html