read sql query output in javascript

I am trying to read the SQL query output in javascript I am using Node.js , Express Engine (a MVC model) to read the MySQL database and display the output on UI using Jade.

I have a file index.js which fetches value of 'password' and 'user_name'from homepage.jade form field. I have to check if the password entered by user matches the password in the database. for which I am querying the database to get a matching record for the entered username and want to fetch the password value for that user and check if it is equal to the form value of password.

router.get('/sample', function(req, res) {


db=mysql.createConnection(config);
    db.connect(function(err){

    });

var formpass= req.body.password;
var user_name= req.body.userName;
var sql="select * from user where user_name= 'monicathaneer'";

    db.query(sql, function(err_query,data)
{

for a in data
pass= a.password;
}

    if(formpass==pass)
    {
        res.render('Login', {
        "Login" : data  });

     }
});

I get errors saying unexpected token near 'a' and unexpected token near 'if' when I run the node. I would like to know how can I can read the password property from the sql output in a .js file.

Your code sample has some syntax errors and lost curly braces. Try this (assuming you're using node-mysql module):

router.get('/sample', function(req, res) {

  var formpass = req.body.password,
      user_name = req.body.userName,
      sql = "select * from user where user_name = 'monicathaneer'";
  var db = mysql.createConnection(config);

  db.connect(function (err) {
    // you should handle the errors here
  });

  db.query(sql, function (err_query, data) {

    // I'm assuming your query will return just 1 row
    // because usernames should be unique
    if (formpass === data[0].password) {
        res.render(
          'Login',
          {"Login": data}); // In your context, 'data' contains the user password...
                            // Do you really want to send it back to the web page?
    }
  });

  db.end(); // you forgot to close your connection.
});

Some considerations:

  • You should not try to handle authentication manually. Consider using a middleware like Passport.js;
  • You don't need to open and close your connection on each request. Try to refactor your code in order to open the connection when the app starts, and use it on demand.