Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

516
Visualizações
TypeError: Cannot read property 'app' of undefined when overwriting res.render

In my project I want to overwrite the res.render method to always add an option, no matter what other options there are. When I try to do it I get the error mentioned above. Here's my current middleware code:

app.use((_, res, next) => {
    const oldRender = res.render;

    res.render = (view, options, callback) => {
        if (typeof options === "function") {
            callback = options;
            options = {};
        }

        options.stops = stops?.data || {};

        oldRender.call(this, view, options, callback);
    };

    next();
});
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

It looks to me like the point of this code is to always pass a particular value to your templates without requiring every caller of res.render() to add that to the data they pass to the template.

The general-purpose way to solve this type of problem is to put a property in res.locals. The template system looks there in addition to the data passed to res.render() and this is the easy way to pass data to all your templates:

app.use((_, res, next) => {
    res.locals.stops = stops?.data || {};
    next();
});

If there's some reason that won't work for you, then the apparent problem to the solution you're trying is that you're using arrow function so the value of this you're using in oldRender.call(this, view, options, callback); is the lexical value of this, not res which is what you need it to be. You can change this:

oldRender.call(this, view, options, callback);

to this:

return oldRender.call(res, view, options, callback);

You can directly pass res instead of trying to use this and you should also return the return value (which will be res) to duplicate the original behavior.


Doc link on res.locals.

A few other answers about res.locals:

Difference between assigning to res and res.locals in node.js (Express)

Is this bad practice for res.locals? (Node.js, express)

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda