How to edit page after rendered with Node.js? [closed]

1

I need every time a page is rendered with any path to be added one paragraph after <body> and another paragraph before </body> .

I'm using Express.js and to do this by taking the string return from app.render and after manipulating it it runs a res.write . But that way I would have to repeat the code for all the routes and my intention is to do it as if it were a middleware run with only app.use .

    
asked by anonymous 14.01.2015 / 23:12

1 answer

1

According to the source code you can pass a callback for the res.render function, if you do not pass a callback you may notice that the express itself provides a default callback that invokes res.send with the rendering result.

You can change the rendered string as you want from this callback, however we know that it is very difficult to change the HTML string in the hand, in this case you can use a module like cheerio to do this manipulation.

Applying to all routes

A mechanism to adopt this solution on all routes would be something like this;

function alterarResposta(next) {
    return function(err, renderedView) {
        if(err) {
            return next(err);
        }

        res.modifyResponse = true;
        res.renderedView = renderedView;
        next();
    }
}

app.get('/helloWorld', function(req, res, next) {
    res.render('helloWorld', alterarResposta(next));
});

app.get('/fooBar', function(req, res, next) {
    res.render('fooBar', alterarResposta(next));
});

// Aqui vem todas as suas outras rotas!

app.use(function(req, res, next) {
    if(!res.modifyResponse) {
        return res.send(res.renderedView);
    }

    //Aqui você modifica sua resposta
    res.send(res.renderedView);
});

NOTE: You can put the change response function in another file .js

Although the paragraphs above answer your question I would not particularly adopt this solution (I would not think about modifying the answer before sending). I would prefer to use a mechanism in the templates themselves, some kind of include or import (I do not know which nomenclature is used in EJS) so that all templates automatically import this additional content. This second approach is less labor-intensive and less error-prone.

    
15.01.2015 / 15:13