learning nodejs 2 - connect middleware

时间:2021-01-29 15:04:57

学习了connect module

nodejs 的中间件方式

var connect = require('connect');
var server = connect.createServer();

// connect.logger 是一个中间件
server.use(connect.logger('dev'));

// 值得学习的是 next 方法
server.use(function(req, res, next) {
if ('/a' == req.url) {
// here do something
} else {
// next is the require chain like java filter china
next();
}
}); server.listen(3000);

connect 的中间件,还包括:

connect.static // 映射静态路径

// web root path
server.use(connect.static(__dirname + '/resource')); // path '/images' point to '/path/to/images'
server.use('/images', connect.static('/path/to/images')); // client side cache
server.use('/js', connect.static('/path/to/bounds', {
maxAge: 10000000 }); // hidden
server.use(connect.static('/path/to/resources', {
hidden: true });

connect.query // 解析GET参数

connect.bodyParser // 解析POST参数

connect.logger // 日志

connect.cookieParser // 解析cookie

connect.session // session

var server = connect(
connect.logger('dev'),
connect.bodyParser(),
connect.cookieParser(),
connect.session({secret: 'my app secret'}),
function(req, res, next) {
if (req.url == '/images') {
// todo ...
} else {
next();
}
}
);

nodejs的代码真是简洁啊~