[英]Express.js middleware for res.send , call function on each res.send()
[英]It is possible to enhance the express.js req and res variables without using a middleware function?
我正在使用express.js在一个宁静的服务工作,我想增强req和res变量,所以例如你可以写类似的东西
app.use(function (req, res, next) {
res.Ok = function (data) {
res.status(200).send(data);
};
res.InternalError = function (err) {
res.status(500).send(err);
};
});
然后
router.get('/foo', function (req, res) {
res.Ok('foo');
})
这将在响应正文中发送'foo'并将状态代码设置为200并且工作正常。
我的第一个问题是,如果可以在没有中间件功能的情况下添加这样的功能,那么可以说在属性或app变量的原型中?
第二个问题是,如果在应用程序级别添加许多具有中间件功能的功能,则会出现性能问题。 此功能是按请求附加到请求和响应对象还是在应用程序启动时附加一次?
我知道Sails框架已经这样做了,但我想知道他们是否也使用中间件功能。
我一直在挖掘并发现请求和响应对象使用__proto__
属性在express中公开。
var express = require('express'),
app = express();
app.response.__proto__.foo = function (data) {
this.status(200).send(data);
};
后来在路由器中
router.get('/foo', function (req, res, next) {
res.foo('test');
});
这将在您的浏览器中打印测试,因此可以在不使用任何中间件的情况下添加功能。
注意:我确信这种方法存在一些缺点(例如,覆盖表达预定义的属性),但出于测试目的和添加非常简单的功能,我认为在性能方面稍微好一点。
我不知道除了使用中间件之外的任何其他方式。 但在我看来,你可以做到以下几点来实现几乎相同的事情。
// Some Route
router.get('/foo', function(req, res, next) {
// ...
if(err) {
res.status(500);
return next(err);
}
return res.send('ok');
});
// Another route
router.get('/bar', function(req, res, next) {
// ...
if(badUserId) {
res.status(400);
return next('Invalid userId.');
}
req.result = 'hello';
return next();
});
router.use(function(req, res) {
// I prefer to send the result in the route but an
// approach like this could work
return res.send(req.result);
});
// Error Middleware
router.use(function(err, req, res, next) {
if(res.statusCode === 500) {
// Log the error here
return res.send('Internal server error');
} else {
return res.send(err);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.