Vue+MySQL+Express

用vue-cli腳手架工具創(chuàng)建一個(gè)基于webpack的Vue項(xiàng)目

安裝node

node官網(wǎng)地址:https://nodejs.org/en/
直接選擇對(duì)應(yīng)的版本安裝就可以了。

查看是否安裝成功

node -v
npm -v
cnpm -v

安裝cnpm

使用npm安裝依賴模塊可能會(huì)很慢,建議換成[cnpm]

<!-- -g表示全局安裝 -->
npm install -g cnpm --registry=http://registry.npm.taobao.org

安裝vue-cli腳手架工具

sudo npm install -g vue-cli

創(chuàng)建一個(gè)項(xiàng)目文件夾,進(jìn)入項(xiàng)目目錄執(zhí)行:

<!--my-project是項(xiàng)目名-->
vue init webpack my-project 

生成my-project項(xiàng)目目錄

Paste_Image.png

安裝vue-resource依賴

一種安裝方式先在 package.json 中對(duì)應(yīng)地方添加,然后執(zhí)行npm install

"dependencies": {
    "vue": "^2.1.10",
    "vue-router": "^2.2.0",
    "vue-resource": "^1.0.3"
},

安裝完成后執(zhí)行,安裝依賴(cnpm install 速度比npm快)

npm install

執(zhí)行如下,進(jìn)行開發(fā)時(shí)調(diào)試

npm run dev

npm的常用命令

  • npm -v #顯示版本,檢查npm 是否正確安裝。
  • npm install express #安裝express模塊
  • npm install -g express #全局安裝express模塊
  • npm list #列出已安裝模塊
  • npm show express #顯示模塊詳情
  • npm update #升級(jí)當(dāng)前目錄下的項(xiàng)目的所有模塊
  • npm update express #升級(jí)當(dāng)前目錄下的項(xiàng)目的指定模塊
  • npm update -g express #升級(jí)全局安裝的express模塊
  • npm uninstall express #刪除指定的模塊

添加 Express 服務(wù)端目錄

在項(xiàng)目根文件夾下創(chuàng)建一個(gè) server 文件夾。然后里面創(chuàng)建下面三個(gè)文件;
和api目錄,api里面建一個(gè)文件

db.js——用來添加 mysql 配置

根據(jù)mysql的IP,端口,用戶名,密碼,數(shù)據(jù)庫(kù)名稱自行修改

代碼如下:

// 數(shù)據(jù)庫(kù)連接配置
module.exports = {
    mysql: {
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'wxd',
        port: '3307'
    }
}

index.js——Express 服務(wù)器入口文件

// node 后端服務(wù)器

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);

// 監(jiān)聽端口
app.listen(3000);
console.log('success listen at port:3000......');

sqlMap.js——SQL 語(yǔ)句映射文件,供 API 調(diào)用

// sql語(yǔ)句
var sqlMap = {
    // 用戶
    user: {
        add: 'insert into user(id, name, age) values (0, ?, ?)'
    }
}
    
module.exports = sqlMap;

api/userApi.js —— 測(cè)試用 API 示例

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

// 連接數(shù)據(jù)庫(kù)
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.username, params.age], function(err, result) {    
        if (err) {       
            console.log(err);
        }        
        if (result) {
            jsonWrite(res, result);
        }
    })
});
module.exports = router;

在項(xiàng)目根目錄下安裝依賴

npm install express mysql body-parser

此時(shí)在 server 文件夾下執(zhí)行node index(這里也可以加載 package.json 中,然后使用 npm 執(zhí)行)看到 success listen at port:3000……即服務(wù)端啟動(dòng)成功。

編寫 vue

Hello.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <form>
      <input type="text" name="username" v-model="userName"> <br>
      <input type="text" name="age" v-model="age"> <br>
      <a href="javascript:;" @click="addUser">提交</a>
    </form>
  </div>
</template>
<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      userName: '',
      age: ''
    }
  },
  methods: {
    addUser() {
      var name = this.userName;
      var age = this.age;
      this.$http.post('/api/user/addUser', {
        username: name,
        age: age
      },{}).then((response) => {
        console.log(response);
      })
    }
  }
}
</script>

這里注意,如果沒有引用vue-resource,this.$http.post是不生效的,還會(huì)報(bào)錯(cuò)
報(bào)錯(cuò)信息:

Uncaught TypeError: Cannot read property 'post' of undefined

解決方案:在main.js中引入vue-resource

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

import VueRouter from 'vue-router'
import VueResource from 'vue-resource'

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

// 此處需要use后,this.$http.get或者this.$http.post才可以
Vue.use(VueRouter)
Vue.use(VueResource)

整個(gè)項(xiàng)目結(jié)構(gòu):

Paste_Image.png

這時(shí)候項(xiàng)目已經(jīng)基本完成,執(zhí)行cnpm install命令安裝依賴

cnpm install 

執(zhí)行如下命令,進(jìn)行開發(fā)調(diào)試

npm run dev

調(diào)試過程中出現(xiàn)問題,可以重新編譯代碼

npm run build

這里,如果執(zhí)行npm run dev后,報(bào)eslint的錯(cuò)誤,可以在build目錄的webpack.base.conf.js文件中,把eslint的代碼注釋掉,重新執(zhí)行npm run dev就不會(huì)報(bào)錯(cuò)了:

ESLint是一個(gè)QA工具,用來避免低級(jí)錯(cuò)誤和統(tǒng)一代碼的風(fēng)格。ESLint被設(shè)計(jì)為完全可配置的,主要有兩種方式來配置ESLint:

  • 在注釋中配置:使用JavaScript注釋直接把配置嵌入到文件中。
  • 配置文件:使用一個(gè)JSON或YAML文件來為全部的目錄和它的子目錄指定配置信息。

注釋的代碼如下:

   // 去掉eslint驗(yàn)證,注釋掉下面的代碼
   // {
   //   test: /\.(js|vue)$/,
   //   loader: 'eslint-loader',
   //   enforce: "pre",
   //   include: [resolve('src'), resolve('test')],
   //   options: {
   //     formatter: require('eslint-friendly-formatter')
   //   }
   // },

執(zhí)行npm run dev,打開一個(gè)頁(yè)面,然后輸入一組數(shù)據(jù),點(diǎn)擊保存,你會(huì)發(fā)現(xiàn)會(huì)報(bào)一個(gè)錯(cuò)誤:

vue-resource.common.js?e289:1071 POST http://localhost:8080/api/user/addUser 404 (Not Found).

這是由于直接訪問8080端口,是訪問不到的,這里需要設(shè)置一下代理轉(zhuǎn)發(fā)。

設(shè)置代理與跨域

vue-cli 的 config 目錄的index.js文件中有一個(gè)proxyTable參數(shù),用來設(shè)置地址映射表,可以添加到開發(fā)時(shí)配置(dev)中

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

即請(qǐng)求/api時(shí)就代表‘http://localhost:3000/api/’,
changeOrigin參數(shù)接收一個(gè)布爾值,如果為true,這樣就不會(huì)有跨域問題了。

經(jīng)過如上一系列操作后,打開頁(yè)面輸入用戶名,年齡,直接點(diǎn)擊提交。數(shù)據(jù)入庫(kù)。~搞定!效果如下:

Paste_Image.png

最后,奉上數(shù)據(jù)庫(kù)user表建表語(yǔ)句:

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

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

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