So, I wanted to move all my mysql query functions to another file and import it as a module, but I'm having trouble in that the function is returning undefined.
index.js:
const express = require('express')
const https = require('https');
const fs = require('fs');
const dbx = require('./databaseconn');
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/example.com/chain.pem')
};
const app = express();
app.use(express.json());
app.use(function(req,res,next) {
if (req.body.action) {
switch (req.body.action) {
case "login":
var user = req.body.username;
var pass = req.body.password;
console.log(dbx.checklogin(user, pass)); // This prints undefined
break;
default:
break;
}
}
});
https.createServer(options,app).listen(8000);
databaseconn.js:
const mysql = require('mysql');
exports.checklogin = function(username, password) {
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'xxxxxxxxxxxxxx',
database : 'users',
});
connection.query('select * from logins where username = ? and password = ?;',
[
username,
password
], function (err, rows, fields) {
if (err) throw err;
if (!rows.length) {
console.log('0');
return {"success":0};
} else {
console.log('1'); // THIS PRINTS
return {"success":1}; // So this should return the JSON
}
})
}
So I see a "1" from the console.log in the databaseconn.js, but the console.log in the index.js file is printing undefined. What am I doing wrong? I also did a super barebones test that works fine so I can't see the difference.
test.js:
const express = require('express');
const test2 = require('./test2');
var t = test2.test();
console.log(t);
test2.js:
exports.test = function() {
return {"success":1};
}