I query data from a database and want to display it on my site. I decided to outsource my SQL statements into a seperat file called select.js. How can I pass the database data into my routes file and there on my site? Now it's always undefined. If I put the SQL select directly into my route then it works fine.
What I got so far:
select.js
const db = require('./config'); //Connection works
//KATEGORIEN LADEN
var sql = 'SELECT * FROM Kategorie';
var Kategorie_data;
db.query(sql, function (err, data, fields) {
if (err) throw err;
Kategorie_data = data; //tried there playing a bit with the var data
});
module.exports = {
kategorie_data: Kategorie_data,
}
snippet route.js
var express = require('express');
var router = express.Router();
var db = require('../query/select');
router.get('/api', function (req, res, next) {
console.log(db.kategorie_data);
res.render('api/api', {kategorie_data: db.kategorie_data });
});
api.ejs
<% if(kategorie_data.length!=0){
var i=1;
kategorie_data.forEach(function(data){
%>
<%=data.Kategorie_Name %>
<% i++; }) %>
<% } else{ %>
No Data Found
<% } %>