个人总结,仅供参考,详细内容请 参考官方教程:
github项目源代码:代码链接
终端下载git clone https://github.com/RobinsonKO/node-blog.git
推荐文章:git详细入门攻略
npm istall express-generator -g
express -h
express -e blog
一个express项目中包含以下几类中间件,熟悉这几类中间件之后,在去分析app.js中的内容就清晰多了。
应用层中间件是通过app实例对象使用app.use()、app.METHOD()使用的,例如:
var app = express();
app.use(function (req, res, next) {
console.log('Time: ',Date.now();
next();
};
app.get('/user, function(req, res ,next) {
res.send('USER');
};
路由层中间件和应用层中间件类似,只是通过Router实例对象使用use()、METHOD()方法,例如:
var express = require('express');
var Router = express.Router();
router.use(function (req, res, next) {
console.log('Time: ',Date.now();
next();
};
router.get('/user, function(req, res ,next) {
res.send('USER');
};
错误处理中间件必须包含4个参数,即使不使用next对象,例如:
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
router.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next router
if (req.params.id == 0) next('route');
// otherwise pass control to the next middleware function in this stack
else next(); //
}, function (req, res, next) {
// render a regular page
res.render('regular');
});
// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id);
res.render('special');
});
从4.x版本之后,Express就不在依赖Connect,除了express.static之外,其他的中间件都作为独立的第三方中间件使用,第三方中间件的使用方法为,例如使用cookie-parser
npm install cookie-parser --save
var CookiePaser = require('cookie-parser);
var app = express();
app.use(CookieParser());
mongodb数据库(作为本地服务?)
node.js开发之express4.0使用mongoose连接mongodb
//app.js
var express = require('express')
, cookieParser = require('cookie-parser')
, session = require('express-session')
, app = express()
app.use(cookieParser()) // required before session.
app.use(session({
secret: 'keyboard cat',
key: 'sid',
cookie: { secure: true, maxAge: 60000 }
})
)
Session数据并不是保存在Cookie中,反而用到了Cookie,所以必须提前使用[cookie-parser]
key
- cookie name defaulting to connect.sid
.store
- session store instance.secret
- session cookie is signed with this secret to prevent tampering.proxy
- trust the reverse proxy when setting secure cookies (via “x-forwarded-proto”).cookie
- session cookie settings, defaulting to { path: '/', httpOnly: true, secure: false, maxAge: null }
// routes/index.js 打印出Cookie、Session
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies);
console.log("Session: ", req.session);
})
通过req.cookies 、 req.session 获取相应cookie,session信息
//app.js
var mongoose = require('mongoose');
, MongoStore = require('connect-mongo')(express);
// Basic usage
mongoose.connect('mongodb://localhost/blog');
app.use(session({
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
//app.js
var flash = require('connect-flash');
app.use(express.cookieParser('keyboard cat'));
app.use(session({
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(flash());
// routes/index.js 测试
router.post('/reg', function(req, res) {
//检查用户两次输入的口令是否一致
if (req.body['password-repeat'] != req.body['password']) {
req.flash('error','两次输入密码口令不一致');
console.log("Session: ", req.session);//错误时,显示flash信息
return res.redirect('/reg');
}
...
}
/* 后台打印出的Session信息
Session: Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
flash: { error: [ '两次输入的口令不一致' ] },
user: null }
*/
flash保存住Session中,通过flash中的变量自会在用户当前和下一次请求中被访问,之后就会被删除,通常与重定位redirect一起使用,可以方便的实现页面的通知和错误信息显示
// routes/index.js
router.post('/reg', function(req, res) {
...
req.session.user = UserEntity;
...
}
function checkLogin(req,res,next) {
if (!req.session.user) {
req.flash('error','未登录');
return res.redirect('/login');
}
next();
}
通过把用户保存到Session中,来区分用户是否登录和区分不同用户
// res.local 属性 把error等属性注册views层全局变量,生命周期为一次request请求,从而实现动态视图
app.use(function(req, res, next){
console.log("Comes to DynamicHelper");
res.locals.user = req.session.user;
res.locals.post = req.session.post;
var error = req.flash('error');
res.locals.error = error.length ? error : null;
var success = req.flash('success');
res.locals.success = success.length ? success : null;
next();
});