Express
Express工程环境配置
安装express
npm install express -g-
Express项目组织生成器自动生成工程结构
<small>/bin: 用于应用启动
/public: 静态资源目录
/routes:可以认为是controller(控制器)目录
/views: jade模板目录,可以认为是view(视图)目录
app.js 程序main文件</small> -
进入工程,安装npm install依赖,然后执行npm start启动程序,在浏览器中访问对应的端口,就会看到如下结果:
E:\nodeTest>npm start> nodetest@0.0.0 start E:\nodeTest > node ./bin/www --debug addr: [object Object] Listening on port 80 GET / 200 30.455 ms - 170 GET /stylesheets/style.css 200 3.780 ms - 111
编写相关代码,整合Express+MySQL
-
新建几个目录
<small>在工程的根目录新建三个目录:
util – 工具方法
conf – 配置
dao – 与数据库交互
目录结构如下:</small>
- 在conf目录中配置mySQL数据库的连接
/**
* Created by hzlinchanglong on 2017/1/23.
*/
// conf/db.js
// MySQL数据库联接配置
module.exports = {
mysql: {
host: '127.0.0.1',
user: 'root',
password: '631020',
database:'client', // 前面建的user表位于这个数据库中
port: 3306
}
}; - 编写SQL语句
/**
* Created by hzlinchanglong on 2017/1/23.
*/
// dao/personSqlMapping.js
// CRUD SQL语句
var person = {
insert:'insert into person(id, name, sex, isVip, address) values(0,?,?,?,?)',
update:'update person set name=?, sex=?, isVip=?, address=? where id=?',
delete: 'delete from person where id=?',
queryById: 'select * from person where id=?',
queryAll: 'select * from person'
};
module.exports = person;
-
在/routes/users.js中添加路由
var express = require('express');
var router = express.Router();
var userDao = require('../dao/userDao');/* GET users listing. */ router.get('/', function(req, res, next) { res.render('updateUser'); }); // 增加用户 router.get('/addUser', function(req, res, next) { userDao.add(req, res, next); }); router.get('/queryAll', function(req, res, next) { userDao.queryAll(req, res, next); }); router.get('/query', function(req, res, next) { userDao.queryById(req, res, next); }); router.get('/deleteUser', function(req, res, next) { userDao.delete(req, res, next); }); router.post('/updateUser', function(req, res, next) { userDao.update(req, res, next); }); module.exports = router;
-
在/dao/userDao.js中实现add、delete、update、queryById、queryAll方法
/**
* Created by hzlinchanglong on 2017/1/23.
*/
// dao/userDao.js
// 实现与MySQL交互
var mysql = require('mysql');
var $conf = require('../conf/db');
var $util = require('../util/util');
var $sql = require('./personSqlMapping');// 使用连接池,提升性能 var pool = mysql.createPool($util.extend({}, $conf.mysql)); // 向前台返回JSON方法的简单封装 var jsonWrite = function (res, ret) { if(typeof ret === 'undefined') { res.json({ code:'1', msg: '操作失败' }); } else { res.json(ret); } }; module.exports = { add: function (req, res, next) { pool.getConnection(function(err, connection) { // 获取前台页面传过来的参数 var param = req.query || req.params; // 建立连接,向表中插入值 connection.query($sql.insert, [param.id, param.name, param.sex, param.isVip, param.address], function(err, result) { // 以json形式,把操作结果返回给前台页面 jsonWrite(res, result); // 释放连接 connection.release(); }); }); }, delete: function (req, res, next) { // delete by Id pool.getConnection(function(err, connection) { var id = +req.query.id; connection.query($sql.delete, id, function(err, result) { if(result.affectedRows > 0) { result = { code: 200, msg:'删除成功' }; } else { result = void 0; } jsonWrite(res, result); connection.release(); }); }); }, update: function (req, res, next) { // update by id // 为了简单,要求同时传name和age两个参数 var param = req.body; if(param.name == null || param.sex == null || param.id == null || param.address == null || param.isVip == null) { return; } pool.getConnection(function(err, connection) { connection.query($sql.update, [param.name, param.sex, param.isVip, param.address, +param.id], function(err, result) { // 使用页面进行跳转提示 console.log('err:' + err); if(result.affectedRows > 0) { res.render('suc', { result: result }); // 第二个参数可以直接在jade中使用 } else { res.render('fail', { result: result }); } connection.release(); }); }); }, queryById: function(req, res, next) { var id = req.query.id; pool.getConnection(function(err, connection) { connection.query($sql.queryById, id, function(err, result) { jsonWrite(res, result); connection.release(); }) }) }, queryAll: function (req, res, next) { pool.getConnection(function(err, connection) { connection.query($sql.queryAll, function(err, result) { jsonWrite(res, result); connection.release(); }); }); } };
在/views目录新建三个jade文件
<small>updateUser.jade</small>
//
Created by hzlinchanglong on 2017/1/24.
extends layout
block content
h1 更新用户资料
form(method='post', action='/users/updateUser')
div.form-row
label
span ID:
input(type='text',name='id')
div.form-row
label
span name:
input(type='text',name='name')
div.form-row
label
span sex:
input(type='text',name='sex')
div.form-row
label
span isVip:
input(type='text',name='isVip')
div.form-row
label
span address:
input(type='text',name='address')
div.form-row
input(type='submit')
<small>fail.jade</small>
//
Created by hzlinchanglong on 2017/1/24.
block content
h1 操作失败!
pre #{JSON.stringify(result)}
<small>suc.jade<small>
//
Created by hzlinchanglong on 2017/1/24.
block content
h1 操作成功!
pre #{JSON.stringify(result)}
<small>在浏览器中运行的结果如下:</small>