1、项目结构目录
—bin
—node_modules
—public
—routes
—views
app.js
package.json
2、routes代码:index.js
var express = require('express');
var router = express.Router();
var mongodb = require("mongodb").MongoClient; //数据库,用mongobd链接,install一下
mongodb.connect("mongodb://127.0.0.1:27017/test", function(err, db) {
db.createCollection("users",{},function(err, user) {
// body...
/* index. */
router.get('/', function(req, res) {
res.render('index', { title: 'index' });
});
/*login*/
router.get('/login', function(req, res) {
res.render('login', { title: 'login' });
});
/*logout*/
router.get('/logout', function(req, res) {
res.render('logout', { title: 'logout' });
});
/*home*/
router.post('/home', function(req, res) {
var query_doc = {userid: req.body.name, password: req.body.password};
console.log(query_doc);
user.find(query_doc).limit(1).toArray(function(err, items){
if(items.length === 1){
console.log(query_doc.userid + ": login success in " + new Date());
res.render('home', { title: 'home' });
}else{
console.log(query_doc.userid + ": login failed in " + new Date());
res.redirect('/');
}
});
});
});
});
module.exports = router;
3、view代码
//layout.jade
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
//index.jade
extends layout
block content
h1 Hwllo world
p welcome to #{title}
a(href="/login") 登陆
//login.jade
extends layout
block content
form(method="post",action="home")
p 用户名
input(type="text" name="name")
p 密码
input(type="password" name="password")
//- input(type="submit",value="登录")
p
button(type="submit",value="登录") 登录
//home.jade
extends layout
block content
p
a(href="logout") 登出
//logout.jade
extends layout
block content
p 正在登出...
script(type="text/javascript").
setTimeout(function(){window.location.href = "/";}, 1000);
4、数据库添加数据:userid:admin,password:123456
5、运行结果
6、用到的代码/网站:
Node:http://www.runoob.com/nodejs/nodejs-tutorial.html
Express官方入门文档:http://www.expressjs.com.cn/starter/installing.html
MongoDB :
—a、启动:mongod –dbpath “数据库位置”
—b、cmd进入mongo
—c、相关指令http://docs.mongoing.com/manual-zh/crud.html
相关示例代码:
http://www.cnblogs.com/hutuzhu/p/4487143.html(单一登陆功能)
https://github.com/nswbmw/N-blog(挺具体全面的)