Vue2+Express+MySQL構(gòu)建前后端分離項(xiàng)目

需要用到

前端:
Vue-cli 快速構(gòu)建項(xiàng)目,開發(fā)前端頁面
Vue-Resource 與后端交互
后端:
Node + Express 僅用于編寫API給前端提供數(shù)據(jù)
MySQL 創(chuàng)建數(shù)據(jù)庫

開始準(zhǔn)備工作

安裝Vue-Cli
http://www.itdecent.cn/p/5c9b489d4103
之前已經(jīng)寫過關(guān)于Vue的安裝,點(diǎn)擊連接
直到npm run dev運(yùn)行起來
vue2本身是基于nodeJs的,此時(shí)node也已經(jīng)安裝好了
Express 是基于 Node.js平臺(tái),快速、開放、極簡的 web 開發(fā)框架,待會(huì)再安裝相關(guān)依賴

搭建后端Express服務(wù)器

在根目錄下創(chuàng)建server文件
1、db.js 數(shù)據(jù)庫mysql連接配置
// 數(shù)據(jù)庫連接配置

module.exports = {
    mysql: {
        host: 'localhost',     //mysql地址127.0.0.1
        user: 'root',     //連接mysql的用戶名和密碼
        password: '',
        database: 'mycake',   //數(shù)據(jù)庫名
        port: '3306',   //mysql端口號(hào)
    }
}

如果以上信息不太清楚,或者還未安裝mysql,請參考
http://www.itdecent.cn/p/023f3a758c05
2、index.js Express 服務(wù)器入口文件

// node 后端服務(wù)器
const cakeList = require('./api/cakeList');
const addUser= require('./api/addUser');
const express = require('express');
const app = express();
// 后端api路由
app.use('/api/cake', cakeList);
app.use('/api/user', addUser);
// 監(jiān)聽端口
app.listen(3000);
console.log('success listen at port:3000......');

3、創(chuàng)建api文件夾
cakeList.js 關(guān)于cake查詢所有數(shù)據(jù)的api

var models = require('../db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
// 連接數(shù)據(jù)庫
var conn = mysql.createConnection(models.mysql);
conn.connect();
// 增加cakelist接口
router.get('/cakelist', (req, res) => {
    var sql ="select * from cake";
    conn.query(sql, (err, result)=>{
        if (err) {
            console.log(err);
        }
        if (result) {
            console.log(result);
            res.json(result);
        }
    })
});
module.exports = router;

4、安裝express+mysql的依賴
在根目錄下

npm install express mysql  --save

注意:--save安裝后并將其保存到依賴列表中,如果不保存依賴列表可以忽略不寫,不寫--save就是臨時(shí)安裝某個(gè)依賴
此時(shí)進(jìn)入 server 文件夾下
執(zhí)行 node index
看到 success listen at port:3000……即服務(wù)端啟動(dòng)成功。

編寫前端vue

1、Hello.vue 頁面

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    } 
  },
  created:function (){
        this.$http.get('/api/cake/cakelist')
       .then((response) => {
        console.log(response.data);
      })
    }
}
</script>

2、安裝vue-resource
vue-resource相當(dāng)于jquery中的ajax
只有安裝vue-resource,$http.get才能生效,不然就會(huì)報(bào)錯(cuò)

npm install vue-resource --save

在main.js中引入vue-resource

import VueResource from 'vue-resource'
Vue.use(VueResource)

來看一下完成后的目錄結(jié)構(gòu)


image.png

從圖上可以看出,前后端是完全分離式開發(fā)
此時(shí)還不能運(yùn)行,因?yàn)榉?wù)器在3000端口上,8081端口訪問不到,這樣運(yùn)行就會(huì)報(bào)Not Found 404錯(cuò)誤

配置跨域

config/index.js
proxyTable參數(shù),用來設(shè)置地址映射表

  dev: {
    env: require('./dev.env'),
    port: 8081,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://127.0.0.1:3000/api/',
        changeOrigin: true,
        pathRewrite: {
            '^/api': ''
        }
      }
    },

即請求/api時(shí)就代表‘http://localhost:3000/api/’,
注意:這里最好使用http://127.0.0.1,因?yàn)槲覍?a target="_blank" rel="nofollow">http://localhost也會(huì)報(bào)同樣的錯(cuò)誤
現(xiàn)在我們可以運(yùn)行啦npm run dev,記住:之前的啟動(dòng)服務(wù)器千萬不要關(guān)閉,再開一個(gè)終端運(yùn)行

image.png

這是我的結(jié)果,說明連接后端成功啦,可以繼續(xù)完成更多的api和頁面啦
此項(xiàng)目地址:https://github.com/ortion/vue2mycake

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. 說明 在數(shù)據(jù)統(tǒng)計(jì)和預(yù)測的過程中,工程師基本都使用現(xiàn)成的算法,工程師的主要工作是根據(jù)具體業(yè)務(wù)邏輯...
    xieyan0811閱讀 1,788評(píng)論 0 2
  • 某夜失眠,輾轉(zhuǎn)反側(cè)難以入睡,腦海中竟出現(xiàn)平時(shí)經(jīng)??吹降男^(qū)群狗各具特色的形象,鮮活有趣。于是起身,寫下了這篇《群狗...
    森之味閱讀 326評(píng)論 0 1
  • 我瑟縮著葉子,想盡量減少水分的流失,我就是那一盆在教室陽臺(tái)上的綠蘿。現(xiàn)在正是孩子們上學(xué)的時(shí)候,處處洋溢著讀書...
    小袁Jill閱讀 668評(píng)論 3 8

友情鏈接更多精彩內(nèi)容