【发布时间】:2016-12-10 16:34:50
【问题描述】:
我想做的是修改响应正文。
为此,我使用了一个在每次请求时都会调用的中间件。 为了实现它,我从 github https://github.com/ccoenraets/nodecellar 获取了一个演示应用程序。我在 server.js 中添加了一个中间件,类似于express logging response body 上给出的示例。
我仍然无法修改响应正文,因为 res.send = function (string) 没有被调用。
下面提到的是代码。请让我知道我在这里做错了什么。
var express = require('express'),
path = require('path'),
http = require('http'),
wine = require('./routes/wines');
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 4000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser()),
app.use(express.static(path.join(__dirname, 'public')));
app.use(logResponseBody);
});
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines/:id', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
function logResponseBody(req,res,next){
var send = res.send;
console.log("send resp is: "+send);
res.send = function (string) {
var body = string instanceof Buffer ? string.toString() : string;
console.log("Body found is: "+body);
body = body.replace(/<\/head>/, function (w) {
return 'Modified head' + w;
});
send.call(this, body);
};
res.on('finish', function(){
console.log("Finished " + res.headersSent); // for example
console.log("Finished " + res.statusCode); // for example
})
next();
}
PS:我正在为类似的问题创建一个新线程,因为我的声望低于 50。因此无法在此处添加 cmets。
【问题讨论】:
标签: node.js express middleware