This code returns an error because 'results(mysql.query)' returns undefined value. I have created a database table of 7~10 rows using mysql command shell and the database works perfectly from both workbench and command shell. is it because I have installed mysql in a wrong way? or code fault? I have tested the very same stuff in a different computer and it worked perfectly from there and suddenly it doesn't work. I didn't copy the file, just wrote/typed the same stuff from memory.
I have searched stackoverflow already and it seems everybody talks about async problem, which isn't really the one in my case.(same thing worked before)
used npm install mysql, mysql version is community 5.7
crudserver.js(main file)
const fs = require("fs"); //filesystem
const ejs = require("ejs");
const mysql = require("mysql");
const express = require("express"); //handles all the middlewares
const bodyParser = require("body-parser"); //handles "POST"
const client = mysql.createConnection({
user:"****",
password:"****",
database:"testdb"
});
let app = express();
app.use(bodyParser.urlencoded({
extended:false
}));
app.listen(52273, function(){
console.log("server running at http://127.0.0.1:52273");
});
app.get("/",function (request,response){
fs.readFile("crudlist.ejs","utf8",function(error,data){
client.query("SELECT * FROM products", function(error,results){
response.send(ejs.render(data,{
data:results,
mytitle:"title1",
mytitlesub:"title2"
}));
});
});
});
crudlist.ejs
<% data.forEach(function (itm,index){ %>
some codes....
<% } >
and it says the 'data' is undefined.
Cannot read property 'forEach' of undefined at eval (eval at compile (F:\mycoding\node_modules\ejs\lib\ejs.js:549:12), :17:12) at returnedFn (F:\mycoding\node_modules\ejs\lib\ejs.js:580:17) at Object.exports.render (F:\mycoding\node_modules\ejs\lib\ejs.js:384:37) at Query._callback (F:\mycoding\crudserver.js:25:25) at Query.Sequence.end (F:\mycoding\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24) at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:398:18 at Array.forEach (native) at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:397:13 at _combinedTickCallback (internal/process/next_tick.js:73:7) at process._tickCallback (internal/process/next_tick.js:104:9)