-2
const express = require("express");
const cors = require('cors');
const dbinter = require('./dbinter');
const bodyParser = require('body-parser');

const PORT = process.env.PORT || 3001;

const app = express();
app.use(cors());

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get("/api", (req, res) => {
  console.log('got req for api');
  res.json({message: "Hello"});
});

app.post("/createuser", (req, res) => {
  //console.log(dbinter.checkUserInfo("a","1"));
  async function sendToFE() {
    const resFromSQL = await dbinter.checkUserInfo(req.body.user[0].name, req.body.user[0].password);
    console.log('response is: ' + resFromSQL);  // returns undefined
    res.send({sqlRes: resFromSQL});
  }
  sendToFE();
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});
const pass = require('./password');
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "t",
  user: "t",
  password: pass.getPass(),
  port: "3454",
  database: "t"
});

//may need to do encryption on both ends in future
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

function createUser(nameRec, passRec) { 
  if (nameRec && passRec) {
    let sql = `INSERT INTO userlogins (name, password) VALUES ('${nameRec}', '${passRec}')`;
    con.query(sql, (err, result) => {
      if (err) throw err;
      console.log("creating user: " + nameRec);
    });
  } else {
    console.log('name still null');
  }
}

//pass sql text from the async function, then return promise
async function checkUserInfo(nameRec, passRec) {
  let queryTxt = `SELECT * FROM userlogins WHERE name = '${nameRec}';`;
  con.query(queryTxt, (err, result) => {
    if (err) throw err;
    if (Object.keys(result).length === 0) {
      createUser(nameRec, passRec);
     }
    console.log('query results' + result);
    return new Promise ((resolve, reject) => {
      console.log('returning promise ' + Object.keys(result).length)
      resolve(Object.keys(result).length);
    })
  });
}

function getCreds(userName, passWord) {
    console.log(pass.getPass());
}

//check incoming for symbols, double check sql injections

module.exports = {getCreds, checkUserInfo}

So this will not tell me if users were found in the db. It returns the correct information from SQL but the code does not wait for the reply. Basically sendToFE needs to wait for a response before running the function. I get this from the console:

Server listening on 3001 response is: undefined Connected! query results[object Object] returning promise 1

Any idea why? It seems to be an issue with checkUserInfo and app.post("/createuser"

Drwooi Poipoi
  • 181
  • 1
  • 2
  • 13
  • _"Basically sendToFE needs to wait for a response before running the function."_ -- `sendToFE()` waits for `dbinter.checkUserInfo()` to complete but the caller of `sendToFE()` does not wait for `sendToFE()` to complete. An asynchronous function always returns a `Promise` and the caller must `await` that promise or chain a `.then()` on it, to resume the processing when the promise is fulfilled. Read about [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). – axiac Feb 24 '23 at 20:52
  • Tried it, moved the async function declaration out of the post function. Called that from an async function, no luck. Changed sendToFE() to sendToFE().then, no luck. If that mozilla link helped my issue would have been solved already – Drwooi Poipoi Feb 24 '23 at 21:49

1 Answers1

0

con.query or the function around it was returning undefined. I finally found a working example to only return it in a promise. This only returns the promise when the query is done.

Function returning "undefined" while trying to query database in node.js

Drwooi Poipoi
  • 181
  • 1
  • 2
  • 13