中间件
什么是中间件
- 处理请求的,本质是函数
- 用户从请求到响应过程中的处理环境分步骤处理,每个步骤调用一个方法完成,这个方法就是中间件(中间处理环节)
- 处理和封装(例如query,postBody,cookie,session),返回一个方法,挂载在req上
- 一定在路由前挂载,因为需要在路由里使用,接收三个参数(req,res,next)
express中的中间件
express中对中间件有几种分类,同一个请求中所有中间件都操作的是同一个req,res
1.应用程序级别中间件
万能匹配,不关心请求路径和请求方法的中间件
-
任何请求都会进入这个中间件
var express = require('express') var app = express() // 类型1:app.use app.use(function(req, res, next){ console.log('请求进来了') // 不调用next()不会进入第二个中间件 next() }) // 配置404中间件 app.use(function(req, res){ console.log('第二个中间件,404了') res.render('404. html') }) app.listen(8888, function() { console.log('running') })
关心请求路径的中间件
-
只要是'/a'开头的路径就可以进去,不关心子路径
-
'/a/b'可
-
'/ab'不可
app.use('/a',function(req, res, next){ // http://localhost:8888/a/b 可进 // http://localhost:8888/a 可进 // http://localhost:8888/ab 不可 // http://localhost:8888 不可 console.log('/a路径请求进来了') })
2.路由级别中间件
-
严格匹配请求路径和方法的中间件
-
严格匹配, '/a'才能匹配到
-
'/a/b' 不可
app.get('/a', function(req, res, next{ // http://localhost:8888/a/b 不可 // http://localhost:8888/a 可进 // http://localhost:8888/ab 不可 // http://localhost:8888 不可 console.log(1) }) app.post('/', function(req, res, next){console.log(2) }) app.pur('/', function(req, res, next){console.log(3) }) app.delete('/user', function(req, res, next){console.log(4) })
3.错误处理中间件
-
全局错误处理,一般放在404处理之后
app.use(function(err, req, res, next){ console.error(err.stack) res.status(500).send('error') })
4.内置中间件
- express.static
- express.json
- express.urlencoded
5.第三方中间件
- body-parser
- compression
- cookie-parser
- morgan
- response-time
- serve-static
- session
配置中间件
-
中间件要挂载后才能使用
app.use(session({ secret: 'coco', resave: false, saveUninitialized: false }) app.use(router)