开发环境
- NodeJS:v0.10.30
- npm:1.4.21
- OS:Win7旗舰版 32bit
- Express:4.2.0
- MongoDB:2.6.3
1 // view engine setup 2 app.set('views', path.join(__dirname, 'views')); 3 //app.set('view engine', 'ejs'); 4 app.engine('html', require('ejs').renderFile); 5 app.set('view engine', 'html');
修改完成后,重命名views/index.ejs为views/index.html。重启服务,访问成功。
2、安装常用库及页面分离
添加bootstrap和jQuery:
E:\project\nodejs-demo> npm install bootstrap bootstrap@3.2.0 node_modules\bootstrap E:\project\nodejs-demo> npm install jquery jquery@2.1.1 node_modules\jquery E:\project\nodejs-demo>
将bootstrap.min.js 和jquery.min.js 和bootstrap.min.css 拷贝到相应的目录下面(如下图)
接下来,把index.html分成三个部分:
- header.html——页面头部区域。
- index.html——页面内容区域。
- footer.html——页面底部区域。
header.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= title %></title> <!-- Bootstrap --> <link href="/stylesheets/bootstrap.min.css" rel="stylesheet" media="screen"> </head> <body screen_capture_injected="true">
index.html
<!--DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> </body> </html--> <% include header.html %> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <% include footer.html %>
footer.html
<script src="/javascripts/jquery.min.js"></script> <script src="/javascripts/bootstrap.min.js"></script> </body> </html>
重启服务,访问成功。
3、路由
登录设计:
访问路径 | 页面 | 描述 |
/ | index.html | 不需要登录,可以直接访问。 |
/home | home.html | 必须用户登录以后,才可以访问。 |
/login | login.html | 登录页面,用户名密码输入正确,自动跳转到home.html。 |
/logout | 无 | 退出登录后,自动跳转到index.html。 |
打开app.js文件,增加路由配置:
//登录 app.use('/', routes); app.use('/users', users); app.use('/login',routes); app.use('/logout',routes); app.use('/home',routes);
打开routes/index.js文件,添加对应方法:
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); router.route('/login') .get(function(req, res) { res.render('login', { title: '用户登录' }); }) .post(function(req, res) { var user={ username: 'admin', password: '123456' } if(req.body.username === user.username && req.body.password === user.password){ res.redirect('/home'); } res.redirect('/login'); }); router.get('/logout', function(req, res) { res.redirect('/'); }); router.get('/home', function(req, res) { var user={ username:'admin', password:'123456' } res.render('home', { title: 'Home', user: user }); }); module.exports = router;
创建views/login.html和views/home.html两个文件:
login.html
<% include header.html %> <div class="container"> <form class="col-sm-offset-4 col-sm-4 form-horizontal" role="form" method="post"> <fieldset> <legend>用户登录</legend> <div class="form-group"> <label class="col-sm-3 control-label" for="username">用户名</label> <div class="col-sm-9"> <input type="text" class="form-control" id="username" name="username" placeholder="用户名" required> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" for="password">密码</label> <div class="col-sm-9"> <input type="password" class="form-control" id="password" name="password" placeholder="密码" required> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-primary">登录</button> </div> </div> </fieldset> </form> </div> <% include footer.html %>
home.html
<% include header.html %> <h1>Welcome <%= user.username %>, 欢迎登录!!</h1> <a class="btn" href="/logout">退出</a> <% include footer.html %>
修改index.html,增加登录链接:
<% include header.html %> <h1>Welcome to <%= title %></h1> <p><a href="/login">登录</a></p> <% include footer.html %>
路由及页面已准备好,重启服务,访问成功。
4、session相关
安装中间件express-session:
E:\project\nodejs-demo> npm install express-session express-session@1.7.5 node_modules\express-session ├── cookie@0.1.2 ├── cookie-signature@1.0.4 ├── on-headers@1.0.0 ├── utils-merge@1.0.0 ├── parseurl@1.3.0 ├── buffer-crc32@0.2.3 ├── depd@0.4.4 ├── debug@1.0.4 (ms@0.6.2) └── uid-safe@1.0.1 (base64-url@1.0.0, mz@1.0.0) E:\project\nodejs-demo>
安装中间件connect-mongodb:
E:\project\nodejs-demo> npm install connect-mongodb \ > kerberos@0.0.3 install E:\project\nodejs-demo\node_modules\connect-mongodb\nod e_modules\mongodb\node_modules\kerberos > (node-gyp rebuild 2> builderror.log) || (exit 0) | E:\project\nodejs-demo\node_modules\connect-mongodb\node_modules\mongodb\node_mo dules\kerberos>node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\ ..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild | > bson@0.2.11 install E:\project\nodejs-demo\node_modules\connect-mongodb\node_m odules\mongodb\node_modules\bson > (node-gyp rebuild 2> builderror.log) || (exit 0) E:\project\nodejs-demo\node_modules\connect-mongodb\node_modules\mongodb\node_mo dules\bson>node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\. .\node_modules\node-gyp\bin\node-gyp.js" rebuild connect-mongodb@1.1.5 node_modules\connect-mongodb ├── connect@1.9.2 (mime@1.2.11, formidable@1.0.15, qs@1.2.2) └── mongodb@1.4.8 (kerberos@0.0.3, readable-stream@1.0.27-1, bson@0.2.11) E:\project\nodejs-demo>
安装中间件mongodb:
E:\project\nodejs-demo> npm install mongodb - > kerberos@0.0.3 install E:\project\nodejs-demo\node_modules\mongodb\node_module s\kerberos > (node-gyp rebuild 2> builderror.log) || (exit 0) - E:\project\nodejs-demo\node_modules\mongodb\node_modules\kerberos>node "C:\Progr am Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\b in\node-gyp.js" rebuild | > bson@0.2.11 install E:\project\nodejs-demo\node_modules\mongodb\node_modules\b son > (node-gyp rebuild 2> builderror.log) || (exit 0) E:\project\nodejs-demo\node_modules\mongodb\node_modules\bson>node "C:\Program F iles\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\n ode-gyp.js" rebuild mongodb@1.4.8 node_modules\mongodb ├── kerberos@0.0.3 ├── readable-stream@1.0.27-1 (isarray@0.0.1, string_decoder@0.10.25-1, inheri ts@2.0.1, core-util-is@1.0.1) └── bson@0.2.11 (nan@1.2.0) E:\project\nodejs-demo>
添加database/settings.js和database/msession.js这两个文件:
settings.js
module.exports = { COOKIE_SECRET: 'ywang1724.com', URL: 'mongodb://127.0.0.1:27017/nodedb', DB: 'nodedb', HOST: '127.0.0.1', PORT: 27017, USERNAME: 'admin', PASSWORD: '123456' };
msession.js
var Settings = require('./settings'); var Db = require('mongodb').Db; var Server = require('mongodb').Server; var db = new Db(Settings.DB, new Server(Settings.HOST, Settings.PORT, {auto_reconnect:true, native_parser: true}),{safe: false}); module.exports = db;
修改app.js文件:
1 var express = require('express'); 2 var path = require('path'); 3 var favicon = require('static-favicon'); 4 var logger = require('morgan'); 5 var cookieParser = require('cookie-parser'); 6 var bodyParser = require('body-parser'); 7 8 //采用connect-mongodb中间件作为Session存储 9 var session = require('express-session'); 10 var Settings = require('./database/settings'); 11 var MongoStore = require('connect-mongodb'); 12 var db = require('./database/msession'); 13 14 var routes = require('./routes/index'); 15 var users = require('./routes/users'); 16 17 var app = express(); 18 19 // view engine setup 20 app.set('views', path.join(__dirname, 'views')); 21 //app.set('view engine', 'ejs'); 22 app.engine('html', require('ejs').renderFile); 23 app.set('view engine', 'html'); 24 25 app.use(favicon()); 26 app.use(logger('dev')); 27 app.use(bodyParser.json()); 28 app.use(bodyParser.urlencoded()); 29 app.use(cookieParser()); 30 //session配置 31 app.use(session({ 32 cookie: { maxAge: 600000 }, 33 secret: Settings.COOKIE_SECRET, 34 store: new MongoStore({ 35 username: Settings.USERNAME, 36 password: Settings.PASSWORD, 37 url: Settings.URL, 38 db: db}) 39 })) 40 app.use(function(req, res, next){ 41 res.locals.user = req.session.user; 42 next(); 43 }); 44 45 app.use(express.static(path.join(__dirname, 'public'))); 46 47 ......
修改index.js文件:
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); router.route('/login') .get(function(req, res) { res.render('login', { title: '用户登录' }); }) .post(function(req, res) { var user = { username: 'admin', password: '123456' } if(req.body.username === user.username && req.body.password === user.password){ req.session.user = user; res.redirect('/home'); } else { res.redirect('/login'); } }); router.get('/logout', function(req, res) { req.session.user = null; res.redirect('/'); }); router.get('/home', function(req, res) { res.render('home', { title: 'Home' }); }); module.exports = router;
本地安装数据库MongoDB,新建用户nodedb。重启服务,访问成功。
5、页面访问控制及提示
访问控制设计:
访问路径 | 描述 |
/ | 任何人都可以访问,不需要认证。 |
/home | 拦截get请求,调用authentication()进行认证,不通过则自动跳转到登录页面。 |
/login | 任何人都可以访问,不需要认证。 |
/logout | 任何人都可以访问,不需要认证。 |
修改index.js文件:
router.get('/home', function(req, res) { authentication(req, res); res.render('home', { title: 'Home' }); }); function authentication(req, res) { if (!req.session.user) { return res.redirect('/login'); } }
重启服务,访问成功。
添加页面提示,修改app.js文件,增加res.locals.message:
app.use(function(req, res, next) { res.locals.user = req.session.user; var err = req.session.error; delete req.session.error; res.locals.message = ''; if (err) { res.locals.message = '<div class="alert alert-warning">' + err + '</div>'; } next(); });
修改index.js文件,增加req.session.error:
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); router.route('/login') .get(function(req, res) { if (req.session.user) { res.redirect('/home'); } res.render('login', { title: '用户登录' }); }) .post(function(req, res) { var user = { username: 'admin', password: '123456' } if (req.body.username === user.username && req.body.password === user.password) { req.session.user = user; res.redirect('/home'); } else { req.session.error='用户名或密码不正确'; res.redirect('/login'); } }); router.get('/logout', function(req, res) { req.session.user = null; res.redirect('/'); }); router.get('/home', function(req, res) { authentication(req, res); res.render('home', { title: 'Home' }); }); function authentication(req, res) { if (!req.session.user) { req.session.error='请先登录'; return res.redirect('/login'); } } module.exports = router;
修改login.html,增加<%- message %>:
5 <legend>用户登录</legend> 6 <%- message %> 7 <div class="form-group">
重启服务,访问成功。输入错误用户名密码: