I am working on a message gateway API assignment, and for that I am building a SQL database to get and send messages through, but I get this error "Cannot read property 'query' of undefined" when I try establishing a connection:
console.log("got get request"); let sql = "SELECT id, Phone, Body FROM Message WHERE `SentFlag` = 0 ORDER BY `ts` LIMIT 1;" db.mycon.query(sql, function (err, result) { console.log("Result: " + JSON.stringify(result)); if(err){ res.send(err); } else { res.json(result[0]); } }); });
Code for importing the MySQL library:
const mysql = require("mysql"); let connection = mysql.createConnection({ host: "localhost", user: "root", password: "password", database: "my_database" }); connection.connect(function (err) { if (err) { console.error("Failed to connect to database- throwing error:"); throw err; } console.log("Connected to database succesfully."); }); // Each Javascript file has an optional export. This export can be anything: here I made the connection object the export. module.exports = connection;
The error is probably at
db.mycon.query(sql, function (err, result)
I have tried several solutions to the same problem with others, but they do not seem to work here. Also, I am pretty new to Node and a little lost. I would really appreciate your help!
https://stackoverflow.com/questions/65784131/cannot-read-property-query-of-undefined-tried-multiple-solutions-but-cannot January 19, 2021 at 08:58AM
没有评论:
发表评论