node菜鸟笔记(1)---Mongodb+express实现简单登陆注册 2017-05-09初学node把express跟mongoose一起简单的应用了一下(node真的好难啊QAQ)
项目结构:
db
存放操作数据库的文件
public
存放静态文件如css跟js文件
routes
存放路由文件
views
存放模板文件(采用ejs模板)
index.js
程序主文件
package.json
存储项目名、描述、作者、依赖等等信息
遵循了 MVC(模型(model/db)-视图(view)-控制器(controller/route)) 的开发模式
db文件夹放置mongoose跟mongodb连接的文件,以及一个User的model () 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 var mongoose = require ('mongoose' );var URL = "mongodb://localhost:27017/mongoosesample" ;mongoose.connect(URL); mongoose.connection.on('connected' , function ( ) { console .log('Mongoose connection open to ' + URL); }); mongoose.connection.on('error' ,function (err ) { console .log('Mongoose connection error: ' + err); }); mongoose.connection.on('disconnected' , function ( ) { console .log('Mongoose connection disconnected' ); }); module .exports = mongoose;
给mongoose.connection添加 error connected disconnected 事件来监听跟mongodb连接失败 连接完成 断开连接的情况1 2 3 4 5 6 7 8 9 10 11 var mongoose = require ('./mongo.js' );var UserSchema = new mongoose.Schema({ username: {type : String , index :true , unique : true }, pswd: String }); var User = mongoose.model('User' , UserSchema);module .exports = User;
其中给User的username设置唯一索引
由于只是理解一下基本的运行原理所以只采用了signin
跟 signup
两个路由及注册跟登陆 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 var express = require ('express' );var User = require ('../db/user.js' );var router = express.Router();router.get('/' , function (req, res ) { res.render('signin' ); }) router.get('/isok' , function (req, res ) { User.findOne({'username' : req.query.username, 'pswd' : req.query.pswd}).exec(function (error, user ) { if (error) { res.send('发生错误' ); } else if (user == null ) { res.send('登陆失败' ); } else { res.send('登陆成功' ); } }) }) module .exports = router;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 var express = require ('express' );var User = require ('../db/user.js' );var router = express.Router();router.get('/' , function (req, res ) { res.render('signup' ); }) router.post('/' , function (req, res ) { var user = new User({ 'username' : req.body.username, 'pswd' : req.body.pswd }) user.save(function (error, user ) { if (error) { res.send('注册失败' ); } else { res.send('注册成功' ); } }); }); module .exports = router;
在注册路由中采用req.body来获得提交的表单的数据,这里要在index.js
的主程序中引用body-parser
模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 var express = require ('express' );var path = require ('path' );var bodyParser = require ('body-parser' );var app = express();app.set('views' , path.join(__dirname, 'views' )); app.set('view engine' , 'ejs' ); app.use(bodyParser.urlencoded({ extended: true })); app.get('/' , function (req, res ) { res.redirect('/signin' ); }); app.use(express.static(path.join(__dirname, 'public' ))); app.use('/signin' , require ('./routes/signin.js' )); app.use('/signup' , require ('./routes/signup.js' )); app.listen(3000 );
测试一下