中间件
Updated:
一、 中间件的介绍
http://expressjs.com/en/guide/using-middleware.html
- 中间件的本质就是一个请求处理方法,我们把用户从请求到响应的整个过程分发到多个中间件去处理,这样做的目的是提高代码的灵活性,动态可扩展的。
- 同一个请求所经过的中间件都是同一个请求对象和响应对象
二、 应用程序级别中间件
万能匹配(不关心任何请求路径和请求方法)1
2
3
4app.use(function (req, res, next) {
console.log('Time:',Date.now())
next()
})
只要是以 ‘/xxx/‘开头的:1
2
3
4app.use('/a', function (req, res, next) {
console.log('Time:',Date.now())
next()
})
三、路由级别中间件
get:
1
2
3app.get('/', function(req, res){
res.send('hello world')
})post:
1
2
3app.get('/', function(req, res){
res.send('Got a POST request')
})put:
1
2
3app.put('/user', funxtion(req, res){
res.send('Got a PUT request at / user')
})delete:
1
2
3app.delete('/user', function (req, res){
res.send('Got a DELETE request at / user')
})
三、错误处理中间件
1 | app.use(function (err, req, res, next){ |
四、 内置中间件
- express.static serves static assets such as HTML files, images, and so on.
- express.json parses incoming requests with JSON payloads. NOTE: Available with Express 4.16.0+
- express.urlencoded parses incoming requests with URL-encoded payloads. NOTE: Available with Express 4.16.0+
五、第三方中间件
- body-parser
- comperssion
- cookie-parser
- morgan
- response-time
- serve-static
- session