1.搭建vue-cli
vue init webpack vue-node
2.安装包依赖并运行
cd vue-node
npm install
npm run dev
3.创建服务端,新建server文件夹
4.安装express+cors中间件(跨域用)+body-parser(解析表单)+mysql中间件
npm install express --save
npm install body-parser --save
npm install cors --save
npm install mysql --save
5.在server文件夹中进行写node相关配置,代码
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json())
const cors = require('cors');
app.use(cors());
// users接口
var users = require('./routes/users');
app.use('/users', users);
// 监听
app.listen(3001, function () {
console.log('success listen...3001');
});
routes/users.js
var express = require('express');
var router = express.Router();
var query = require('../db.js');
router.get('/', function (req, res, next) {
const sqlStr = 'select * from userlist'
const sqlParams=null
query(sqlStr,sqlParams,function (err,results) {
if (err) return res.json({ err_code: 1, message: '资料不存在', affextedRows: 0 })
res.json({ retCode: 200, data: results, affextedRows: results.affextedRows })
res.end();
})
});
router.post('/add', function (req, res, next) {
const sqlStr = 'insert into userlist set ?'
const sqlParams=req.body
sqlParams.id =new Date().getTime()
query(sqlStr,sqlParams,function (err,results) {
if (err) return res.json({ err_code: 1, message: err, affectedRows: 0 })
res.json({ retCode: 200, message: '恭喜成功', affectedRows: results.affectedRows })
res.end();
})
});
router.use('/delete', function (req, res) {
let sqlStr = 'DELETE FROM userlist where id='+req.body.id;
const sqlParams=null
query(sqlStr,sqlParams,function (err,results) {
if (err) return res.json({ err_code: 1, message: err, affectedRows: 0 })
res.json({ retCode: 200, message: '删除成功', affectedRows: results.affectedRows })
res.end();
})
});
module.exports = router;
db.js
const mysql = require("mysql");
//连接上数据库(连接池)
const conn = mysql.createConnection({
host: 'localhost',//数据库地址
user: 'root',//账号
password: '123456',//密码
database: 'mytest',//库名
port:'3306', //端口号
multipleStatements: true //允许执行多条语句
});
conn.connect();
/*封装数据库操作方法query--用于增删改查*/
const query=function(sql,sqlParams,callback){
conn.query(sql,sqlParams,function(qerr,vals,fields){
callback(qerr,vals,fields);
});
};
module.exports=query;