Alper Berber
Alper Berber

Reputation: 71

ExpressJS function can't return

I've been trying to develop an app working on Electron with an Express webserver. I also use mysql npm package for database stuff. But there's something wrong with the login function and I wasn't able to find the problem. I hope you could help.

server.js

function userLogin(data){

  con.query(`SELECT * FROM players WHERE player_username = '${data.login_username}'`, (err, result, fields) => {
  if (err) throw err;

  var compare = bcrypt.compareSync(data.login_password, result[0].player_password);

      if(compare == true) {
          return "1";
      }
      else{
          return "0";
      };
  });
};

app.route('/login').post((req,res) => {
 res
  .json(userLogin(req.body))
  .end();
});

Everything is defined. No errors are shown but the function can't return, I don't understand why. If I add a console.log above return, it logs the result so the query is also OK, but the function doesn't return anything, literally anything.

Upvotes: 0

Views: 168

Answers (2)

djfdev
djfdev

Reputation: 6037

Since userLogin is an asynchronous function, you can't just call it like a normal function and expect it to return a value. Instead, you should work on its results from inside the callback of con.query when they are available, like so:

app.route('/login').post((req, res) => {
  con.query(`SELECT * FROM players WHERE player_username = '${data.login_username}'`, (err, result, fields) => {
    var compare = bcrypt.compareSync(data.login_password, result[0].player_password);
    res.json(compare ? "1" : "0").end();
  });
});

Upvotes: 1

Dhananjai Pai
Dhananjai Pai

Reputation: 6005

You have to wait for the query to complete before sending the response. One way is to convert it into Promise and another is to use a callback

function userLogin(data, onComplete){

 con.query(`SELECT * FROM players WHERE player_username = '${data.login_username}'`, (err, result, fields) => {
  if (err) throw err;
  var compare = bcrypt.compareSync(data.login_password, result[0].player_password);
      if(compare == true) {
          onComplete("1"); // do callback function
      }
      else{
          onComplete("0");
      };
  });
};

app.route('/login').post((req,res) => {
 userLogin(req.body, (val) => {res.json(val).end(); } ) // pass the function as callback
});

Upvotes: 0

Related Questions