export result of a nodedels middelware to a static js file

0

I am working on NODEJS and express, in my middelware routes / md.js file I process a request to the database and as a result I have an ARRANGEMENT.

I need that arrangement to be read by a static public / js / estatico.js file that is called directly by the HTML.

Any recommendations?

 session
    .run("MATCH (n: Portal) RETURN n ORDER BY n.nombre ")
    .then(function(result){
      var portalArr =[];

      result.records.forEach(function(record){
        vCabeza.push({//guarda los nombre de cada png
          nombre: record._fields[0].properties.nombre
        });
      });

The code runs without problem, if I insert it directly on the page with a render of ejs it prints the names of the png files. But what I need is to be able to read the names of the file from the js that I call from the html so that the images are inserted

const vCabeza=["mChina.png","mGorro.png", "mLentes.png", "mPirata.png"];//Actualmente esta constante hace que funcione la pagina, lo que necesito es que el valor de esta constante, provenga de busqueda arrojada por la base de datos.


function construyeHTML(img){
		var valor=[]; var top=7; var left=22;

	img.forEach (function(n){ //corro el arreglo donde están los nombres de los archivos
		var codigo= '<div class="itemPerfil" id="${valor.length}" style=" top:${top}px; left:${left}px;" onmouseover="getId(this)" onclick="getIdClick(this)"> <img src="imagenes/mikaOutfit/${n}"> </div>';
		switch(valor.length){ //elige los valores too y left del estilo de acuerdo a la posición que ocupará y guarda el codigo en un arreglo
			case 0:
			valor.push(codigo);
			left=left+148;
			break;

			case 4: case 8: case 12: case 16:
			left=2;
			top=top+58; 
			valor.push('<div class="itemPerfil" id="${valor.length}" style=" top:${top}px; left:${left}px;" onmouseover="getId(this)" onclick="getIdClick(this)"> <img src="imagenes/mikaOutfit/${n}"> </div>');
			left=left+148;
			break;

			default:
			valor.push(codigo);
			left=left+148;
		}

		var items=document.getElementById("contenedorItems"); //toma el div del html
		valor.forEach(function(a){//corre el arreglo e inseta el código en la página
		items.innerHTML = valor;
		});

	});
}//fin de function construyeHTML

function perfilItems(variable) { //recibe la orden del HTML y ejecuta la función
	construyeHTML(variable);
} //fin de function perfilItems
<html>
<head>
<meta charset="UTF-8">
<title>Womg</title>
<link  rel="stylesheet" type="text/css" href="css/armario.css"/>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/armario.js"></script>

</head>

<body background="imagenes/fondoRojo.jpg" >




  <div id="pantalla">
  		<div id="contenedorItems"> </div>
  		<div id="nombreItem"> a<br>q<br>u<br>i<br><br>n<br>o<br>m<br>b<br>e<br> </div>
  		<img class="mika" src="imagenes/espacioItems.png" usemap="#controles" alt="fondo">
  			<map name="controles" id="controles">
    				<area shape="rect" coords= "1479,265,1579,365"  onClick="perfilItems(vCabeza)">
  			</map>
    
asked by mmcuervo 20.03.2018 в 04:26
source

1 answer

1

What you want to do does not seem like a use case for a middleware, since it is executed when you make a request, which would change the content of the file and producing an eventual race condition .

It would be better if in the path that renderea your template you will pass the value of vCabeza as template variable:

app.get('/', function(req, res, next) {

    session
    .run("MATCH (n: Portal) RETURN n ORDER BY n.nombre ")
    .then(function(result){
      var vCabeza =[];

      result.records.forEach(function(record){
        vCabeza.push({//guarda los nombre de cada png
          nombre: record._fields[0].properties.nombre
        });
      }); 

      res.render('plantilla', { vCabeza: vCabeza });  
    });

});

And then use it in your template as:

onClick="perfilItems(<%= vCabeza %>)"

(I do not know what is session since you can ask questions, so I infer that it is not the express session, nor am I sure of the ejs syntax because I use handlebars, but as I say, the correct thing is to pass vCabeza as a variable of the template and not by a script written on the fly).

If different routes are going to use vCabeza then it might make sense to use a middleware like this:

app.use(function(req, res, next) {

   session
   .run(...)
   .then(function(result) {
      ...código que llena vCabeza...
      req.vCabeza = vCabeza;
      next();
   });

});

And then call the render with

res.render('plantilla', { vCabeza: req.vCabeza }); 
    
answered by 20.03.2018 / 13:13
source