Engine EJS + Javascript, sharing variables

Asked

Viewed 78 times

-1

const express = require('express');
const bodyparser = require('body-parser');
const redis = require('redis');
const fatorialFuncao = require('./fatorial');

const PORT = process.env.PORT || 8080;
const REDIS_PORT = process.env.PORT || 6379;

const cache = redis.createClient(REDIS_PORT);

const app = express();

app.set('view engine', 'ejs');

app.use(express.static('public'));
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());

cache.on('connect', () => {
   console.log('Redis is ready');
});

cache.on('error', (e) => {
   console.log('Redis error', e);
});

function getCache(key) {
   return new Promise((resolve) => {
      cache.get(key, (err, value) => {
         if (err) {
            PromiseRejectionEvent(err);
         } else {
            resolve(value);
         }
      });
   });
}

function setCache(key, value) {
   cache.set(key, value, 'EX', 10000, (err, value) => {
      if (err) {
         console.log(err);
      } else {
         console.log('Os parâmetros foram cadastrados no cash com sucesso');
      }
   });
}

app.get('/', (req, res) => {
   res.render('index');
});

app.post('/calculofatorial', async (req, res, next) => {
   let id = req.body.s1;
   let valueId = await getCache(`fatorial:${id}`);

   if (valueId) {
      res.send(
         `O fatorial de ${id} é ${valueId}. Obs.: Essa cálculo foi recuperado do cache.`,
      );
   } else {
      if (parseInt(req.body.s1) > 0 && parseInt(req.body.s1) < 171) {
         let calculation = fatorialFuncao(parseInt(req.body.s1));
         const msgValidacao =
            'Obs.: Essa operação não estava armazenada em cache.';

         setCache(`fatorial:${id}`, calculation);
         res.send(`O fatorial de ${id} é ${calculation}. ${msgValidacao}`);
      } else {
         let msgErro = 'Obs.: digite um valor válido';
         res.send(msgErro);

         response.render('index', {
            msgErro,
         });
      }
   }
});

app.listen(PORT, () => {
   console.log(`App listening on port ${PORT}`);
});

will it be possible for me to take the variables below and put in render('index')?

let id = req.body.s1;
let valueId = await getCache(`fatorial:${id}`)

and how to make the route app.post('/calcularfatorial', ...) returns to ('/') after calculation?

1 answer

0

For ejs to have access, have you ever tried to "export" the object inside render? ex.:

res.render('/nome_da_rota', { objeto aqui });

And to redirect to any other route just type:

res.redirect('/rota_que_deseja_redirecionar');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.