我如何在不同的文件中使用/更改 2 个“res.render”?

问题描述

我不知道“res.render”是否可以使用两次。错误是:

C:\ReactVap\vapinto\src\controller\LaunchController.js:45
    return res.render('index',{ launch })
               ^

TypeError: Cannot read property 'render' of undefined

路由器我有这个:

routes.get('/index',(req,res) => {
    if (req.isAuthenticated()) {
      // console.log(req.user)
      res.render('index',LaunchController.index,{user:req.user});
    } else {
      res.render('login',{
        title: 'Home',user: req.user,message: res.locals.message,});
    }
  }
)

在控制器中我有这个:

async index(req,res) {
    const lancamentos = await Launch.get()

    let saldoAnterior = 0;

    let launch = lancamentos.map((item) => {     
       // Intl.NumberFormat('pt-br',{style: 'currency',currency: 'BRL'}).format(money)
      // .toLocaleString('pt-br',currency: 'BRL'})
      // .toFixed(2).replace('.',',')

      const dataFormatada = LaunchUtils.dataFormatada(item)
      const receita = LaunchUtils.receita(item)
      const despesa = LaunchUtils.despesa(item)

      const saldoAtual = receita - despesa
      const saldo = saldoAnterior + saldoAtual;
      saldoAnterior = saldo;  

      return{        
        ...item,dataFormatada,receita,despesa,saldo        
      }      
    })

    const month = '';
    if(month > 0) {
      launch = launch.filter(item => {    
        const month = req.query.month;
        const data = new Date(item.data);
        const dataString = (data.getFullYear() + "-" + ((data.getMonth() + 1)) + "-" + (data.getDate() ))
        
        return LaunchUtils.formatDate(dataString).getMonth() == month 
      })
    } 
    return res.render('index',{ launch })
  }

解决方法

您可以在一个公共文件中完成渲染

示例:

module.exports = {

  renderApp(res,config){
    const defaults = {
        let a = 10,...config
     };

     return res.render('index',defaults) // index path should've been set (app.set(....))
  }

}

无论您想在何处使用渲染,都可以导入它并将其与适用的配置一起使用