Skip to content

Middleware that needs to modify res.body #1583

@nickpack

Description

@nickpack

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions