中间件内容
功能:
- 执行任何代码
- 修改请求的响应对象
- 终结请求-响应循环
- 调用堆栈中的下一个中间件。
如果中间件没有终结请求或响应循环 , 那么必须调用next() 将控制权交给下一个中间件。
类型:
- 应用级中间件
- 路由级中间件
- 错误处理中间件
- 内置中间件
- 第三方中间件。
- 应用级中间件
应用级中间件指绑定到app对象(var app = express();)上的app.get/post…,和app.use()方法内部的中间件。
app.get('/',function (req,res,next) {
console.log("get1");
next();//当前中间件队列里面的下一个中间件 即是下一个函数
},function (req,res,next) {
res.send("get2");
console.log("log2");
next();
});
//结果
控制台输出get1和log2。
浏览器输出get2。
跳过中间件队列 到下一个路由 使用 next(‘route’),需要注意的是这个方法只能在应用级中间件和路由级中间件使用。
app.use('/user/:id', function(req, res, next) {
//console.log('Request URL:', req.originalUrl);
console.log("this is id test");
if(req.params.id == 0){
next('route');//跳转到下一个路由
}else{
next();
}
next();
}, function (req, res, next) {
//这个中间件不会被执行 id ==0 的时候
//console.log('Request Type:', req.method);
next();
});
app.use('/user/:id',function (req,res,next) {
console.log("this is new route");
// res.encoding = 'utf8';
res.send("next route");
});
- 路由级中间件
路由级中间件和应用级中间件想类似 ,只是它绑定的对象为express.Router(), var router = express.Router();
使用的是router.use()或者router.get/post…方法
var express = require('express');
var router = express.Router();
var app = express();
//没有挂载路径的中间件 通过该路由的每个请求都会执行该中间件
router.use(function (req,res,next) {
console.log('all route');
next();
});
//一个中间件栈 ,处理指向 /user/:id 的GET 请求
router.get('/user/:id',function (req,res,next) {
console.log('this is get request');
if(req.params.id === 0){
next('route');
}else {
next();
}
},function (req,res,next) {
console.log('i am the queue with you');
res.write('i am the queue with you');//res.write不会中断请求响应循环
next();
});
router.get('/user/:id',function (req,res,next) {
console.log('new router');
res.end('new router');
next();
});
//将路由挂载至应用
app.use('/',router);
app.listen(3000);
- 错误处理中间件
错误处理中间件有4个参数,定义错误处理中间件时必须使用和这4个参数。即是不需要next对象,也必须在签名中申明,否则中间件会被识别为一个常规中间件,不能处理错误。
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
- 内置中间件
express.static(root,[options]) 托管静态资源,参数 root提供静态资源的根目录,可选的options的参数属性如下
属性 | 描述 | 类型 | 缺省值 |
---|---|---|---|
dotfiles | 是否对外输出文件名以(.)开头的文件。可选值为 “allow”,”deny”,”ignore” | String | ignore |
etag | 是否启用 etag 生成 | Boolean | true |
extensions | 设置文件扩展名备份选项 | Array | [] |
index | 发送目录索引文件,设置为 false 禁用目录索引 | Mixed | index.html |
lastModified | 设置 Last-Modified 头为文件在操作系统上的最后修改日期。可能值为 true 或 false。 | Boolean | true |
maxAge | 以毫秒或者其字符串格式设置 Cache-Control 头的 max-age 属性。 | Number | 0 |
redirect | 当路径为目录时,重定向至 “/”。 | Boolean | true |
setHeaders | 设置 HTTP 头以提供文件的函数。 | function |
示例
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
}
}
app.use(express.static('public', options));