0

I am new in nodejs. I am creating a basic API to get record by id. Everything is working fine. It is returning user data from database. But when i use password variable from response in same function it give me empty value whereas i am getting value in response. I think this is async issue but i dont know how to fix it.

This is API code

var express = require('express');
var db = require('../db/database');
var bcrypt = require('bcrypt');

const router = express.Router();

router.get("/:userId", (req, res, next) => {
    let uid = req.params.userId;

    db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data)=> {
        if(!err) {
            if(data && data.length > 0) {
                var message = '';
                if(data.u_password){
                    //var pass = data.u_password;

                    if(bcrypt.compare('123456', data.u_password)) {
                     // Passwords match
                        message = 'Passwords match';
                    } else {
                     // Passwords don't match
                        message = 'Passwords dont match';
                    }
                }
                res.status(200).json({
                    message:message,
                });
            } else {
                res.status(200).json({
                    message:"User Not found."
                });
            }
        } 
    });    
});

database.js

var mysql = require('mysql');

const pool = mysql.createPool({
            connectionLimit : 10,
            host: 'localhost',
            user: 'root',
            password: '',
            database: 'lost_and_found',
            debug    : false 
            });   

function executeQuery(sql, callback) {
    pool.getConnection((err,connection) => {
        if(err) {
            return callback(err, null);
        } else {
            if(connection) {
                connection.query(sql, function (error, results, fields) {
                connection.release();
                if (error) {
                    return callback(error, null);
                } 
                return callback(null, results);
                });
            }
        }
    });
}

function query(sql, callback) {    
    executeQuery(sql,function(err, data) {
        if(err) {
            return callback(err);
        }       
        callback(null, data);
    });
}   

module.exports = {
    query: query
} 

Response

{"message":""}
5
  • Let me know if any issues you are still facing or if the answer has helped you, please accept the answer Commented Jul 30, 2019 at 7:13
  • Always giving same result 'Passwords dont match'. When i tried console.log(data.u_password) it gave me undefined. Commented Jul 30, 2019 at 9:07
  • If data.u_password is undefined, then password will obviously will not match 123456. Make sure, data.u_password is defined Commented Jul 30, 2019 at 9:08
  • data is the response of API and i want to use u_password variable of response. But i think bcrypt is executing before the API response. Commented Jul 30, 2019 at 9:41
  • Please check the updated answer Commented Jul 30, 2019 at 9:57

1 Answer 1

1

Please change the bcrypt.compare code to following code. It is a callback function:

bcrypt.compare('123456', data.u_password, function(err, result) {
    if (err) {
        // Passwords don't match
        message = 'Passwords dont match';
    } else {
        // Passwords match
        message = 'Passwords match';
    }
    res.status(200).json({
        message:message,
    });
})

EDIT 1: Please update the method to following logic:

db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data) => {
    if (err) {
        throw err;
    }
    if (data && data.length > 0) {
        var message = '';
        if (data.u_password) {
            bcrypt.compare('123456', data.u_password, function (err, result) {
                if (err) {
                    // Passwords don't match
                    message = 'Passwords dont match';
                } else {
                    // Passwords match
                    message = 'Passwords match';
                }
                res.status(200).json({
                    message: message,
                });
            })
        }
        res.status(200).json({
            message: "User Not found."
        });
    }
    res.status(200).json({
        message: "User Not found."
    });
});  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.