express配合sequelize操作数据库
—解放直接操作数据库,从orm做起???
1.express直接用express-generator 生成
1 2 3 4
| $ npm install express-generator -g $ express -f --hbs $ npm install
|
2.在目录上创建相应文件夹
1 2 3 4 5
| $ mkdir config && cd config && touch db.js $ mkdir models
|
3.安装sequelize&&mysql
1 2
| $ npm install i --save sequelize $ npm install i --save mysql
|
4.编辑db.js
1 2 3 4 5 6 7 8 9 10
| var Sequelize = require('sequelize'); module.exports = new Sequelize('test', 'root', null, { host: 'localhost', dialect: 'mysql', pool: { max: 5, min: 0, idle: 10000 } });
|
5.进入models新建user.js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| var Sequelize = require('sequelize'); var sequelize = require('../config/db'); var User = sequelize.define('user', { userName: { type: Sequelize.STRING }, email: { type: Sequelize.STRING } }, { freezeTableName: false }); var user = User.sync({ force: false }); exports.addUser = function(userName, email) { return User.create({ userName: userName, email: email }); }; exports.findByName = function(userName) { return User.findOne({ where: { userName: userName } }); }; exports.findById = function(id) { return User.findOne({ where: { id: id } }); };
|
6.进入routes修改user.js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| var express = require('express'); var router = express.Router(); var user = require('../models/user'); router.get('/', function(req, res, next) { if(req.query.id){ user.findById(req.query.id).then(function(user){ res.send(user.userName); }); }else{ res.send('hello users'); } }); router.get('/addUser', function(req, res, next) { user.addUser('llan', 'llan@163.com').then(function() { return user.findByName('llan'); }).then(function(user) { res.send(user.userName); }); }); module.exports = router;
|
7.跑服务
8.看结果
浏览器输入127.0.0.1:3000
—>完美运行express示例界面(与前面做的无关系???)
浏览器输入127.0.0.1:3000/users
—>见到我们定义的hello users
浏览器输入127.0.0.1:3000/users/addUser
—>界面出现llan(这货就是从数据库通过userName读出来的)
浏览器输入127.0.0.1:3000/users?id=1
—>界面出现llan(通过id获取)