本文链接地址: 理解Node.js中间件以及Connect 模块
刚开始学习Express的时候,在app.js中发现app.use,当时比较困惑。
1 | app.use(express.favicon()); |
2 | app.use(express.logger( 'dev' )); |
3 | app.use(express.bodyParser()); |
4 | app.use(express.methodOverride()); |
6 | app.use(express.static(path.join(__dirname, 'public' ))); |
这里其实就是定义使用了中间件(Middleware)。Express框架实际上是依赖Connect创建的,这里的use方法是Conncet提供的,它用来注册一个中间件到Connect 中间件队列。
什么是中间件?
我的理解是这样的,中间件就是类似于一个过滤器的东西,在客户端和应用程序之间的一个处理请求和响应的的方法。
什么是Connect?
Connect 是Node.js中的一个模块,可以用来创建中间件的一个框架,它自身已经包装了Node的HTTP模块的Server以及Server的req和res的对象。它干的活其实就是处理请求,然后响应客户端或是让下一个中间件继续处理,它的原型是这个样子的
1 | function (req, res, next) { |
当next回调函数被调用,中间件就完成工作并传递到下一个中间件,如果没其他中间件则进入到应用逻辑继续执行。
下面来写一个简单的脚本,自己注册2个中间件来理解下:
01 | var connect = require( 'connect' ), |
02 | http = require( 'http' ); |
08 | function access(req,res,next){ |
09 | var now = new Date().getHours(); |
10 | if (now <13 || now >18){ |
11 | res.writeHead(503,{ 'Content-Type' : 'text/plain' }); |
12 | res.end( '下午1点到6点之外禁止访问!' ); |
18 | function test(req,res){ |
19 | res.writeHead(200,{ 'Connect-Type' : 'text/plain' }); |
20 | res.end( 'this is test page' ); |
23 | http.Server(app).listen(3000); |
这这段代码中,我们注册了2个中间access和test到中间件队列中,这里需要注意的一点就是,Connect是流式处理。通过执行这段代码以后,浏览器访问以下体会吧!
参考:
Express API中提供的中间件 http://expressjs.jser.us/api.html
Connect 中间件 http://www.senchalabs.org/connect/