Eh. . . hello all over the world, they'll see I've been learning one day so if I come to say nonsense and be stupid sorry. I have a small site that I am connecting to mysql with node, but to unburden code I wanted to use module as in java but I have problems. The app makes a request to a js that believes that it has a function that connects to a BD and return (I think) the result, when I call the function it returns a null and then does what I request, it is something Very strange maybe I'm not being very descriptive so I'll leave the code, sorry I'm a beginner.
server.js:
const express = require('express');
const mysql = require("./conetionBD");
var app = express();
app.set('view engine','pug');
app.use("/css", express.static(__dirname+"/css"));
app.get('/',(request,reponse)=>{
console.log("Probando conexcion a mysql . . .");
const ingredientes = mysql.getIngredients();
console.log(ingredientes);
console.log("Prueba terminada");
//reponse.render('recetas',{ing:ingredientes });
reponse.writeHead(200,{"Content-type":"text/html"});
reponse.end();
});
app.listen(8080);
console.log("Servidor en linea");
connectionBD.js:
console.log("----Iniciando conexcion");
const mysql = require('mysql');
var ingredientes = null;
console.log("----Conecatcando");
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "zazem18",
database: "cibus"
});
module.exports = {
getIngredients: function(){
var resultado = null;
con.connect((err)=>{
console.log("----Obteniendo datos, "+err);
if(err) console.log("Error al conectarse");
console.log("----Saltando error");
con.query("select * from cat_units", (errr,result,field)=>{
console.log("----Seleccionar datos");
if(errr)console.log("Error al obtener datos");
console.log(result);
resultado = result;
});
});
return resultado;
}
}
Result in console:
----Iniciando conexcion
----Conecatcando
Servidor en linea
Probando conexcion a mysql . . .
null
Prueba terminada
----Obteniendo datos, null
----Saltando error
----Seleccionar datos
[ RowDataPacket { id_uni: 1, uni_uni: 'cucharada' },
RowDataPacket { id_uni: 2, uni_uni: 'gramo' },
RowDataPacket { id_uni: 3, uni_uni: 'kilogramo' },
RowDataPacket { id_uni: 4, uni_uni: 'libra' },
RowDataPacket { id_uni: 5, uni_uni: 'litro' },
RowDataPacket { id_uni: 6, uni_uni: 'onza' },
RowDataPacket { id_uni: 7, uni_uni: 'onza líquida' },
RowDataPacket { id_uni: 8, uni_uni: 'taza' },
RowDataPacket { id_uni: 9, uni_uni: 'pieza' },
RowDataPacket { id_uni: 10, uni_uni: 'pisca' },
RowDataPacket { id_uni: 11, uni_uni: 'al gusto' },
RowDataPacket { id_uni: 12, uni_uni: 'manojo' },
RowDataPacket { id_uni: 13, uni_uni: 'hoja' },
RowDataPacket { id_uni: 14, uni_uni: 'Lata' },
RowDataPacket { id_uni: 15, uni_uni: 'Loncha' } ]