中间件内容
功能:
类型:
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");
});
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);
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
属性 | 描述 | 类型 | 缺省值 |
---|---|---|---|
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));