Hi, I recently upgraded to 3.x and have just discovered that res.write was removed, and thus some of my middleware doesn't work, the only logical place I can see to replace these is res.send but I seem to be causing responses to not return doing this, consider this simple example:
this.use(function(req, res, next){
var send = res.send;
res.send = function (string) {
var body = string instanceof Buffer ? string.toString() : string;
body = body.replace(/<\/body>/, function (w) {
return 'foo' + w;
});
if (string instanceof Buffer) {
this.body = new Buffer(body);
} else {
this.body = body;
}
send.call(this);
};
next();
});
If I send the raw body instead of the res object, it will crap out because req is lost, with it like this the http response never returns though express seems to think it has, happily dropping a GET in the terminal. I have looked at these requests, and the body is indeed as it should be with 'foo' before the end body tag, it just never gets sent to the browser.
Am I doing something blindingly stupid, or is there an issue/reason for not modifying the body after the view has been rendered?
as seen in the documentation
http://expressjs.com/api.html#res.send
it appears what you need is
this.use(function (req, res, next) {
var send = res.send;
res.send = function (string) {
var body = string instanceof Buffer ? string.toString() : string;
body = body.replace(/<\/body>/, function (w) {
return 'foo' + w;
});
send.call(this, body);
});
next();
};
One another note, that is some strange middleware you got going :dancer:
Hi, I recently upgraded to 3.x and have just discovered that res.write was removed
res.write() was never removed
@hallas Thanks for the help - the reason for the crazy middleware is grunts auto-reload task (needs to inject some js into the page when running)
@jonathanong Interesting, If I hook res.write instead of send it never fires, admittedly I am using another layer on top of express (locomotive) but I couldnt see any reason why.
express-mung is designed for this.
express-mung saved my life :-)
Thanks @richardschneider
Most helpful comment
as seen in the documentation
http://expressjs.com/api.html#res.send
it appears what you need is