Tuesday, 6 June 2017

returns null mysql nodejs

please have a look at dbfn.js file

    /*
    database function file;
*/

var db = require('./connection');

function check_conn(){
    if(db){
        console.log('We are connected to Database server'.bgGreen);
        return true;
    }else{
        console.log('We are not connected to DataBase server'.bgRed);
        return false;
    }
}

module.exports = {

    testCon : function(){
        if(check_conn() === true){
            return 'We are connected to DB';
        }else return 'We are not connected to DB';
    },

    get_user : function(){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                return err;
            }
            if(results){
                console.log(results);
                return results;
            }
            console.log('nothing...');
        });
    }

};

Now, look at routes.js file

var db = require('./dbfn');

module.exports = function(app){

    /*
        Routing starts here
    */

    //root route
    app.get('/', function(req, res){
        res.render('index.ejs');
    });

    //test route
    app.get('/test',function(req,res){

        var x = db.get_user();
        console.log(x);
        res.writeHead(200, {'Content-Type': 'text/json'});
        res.json(x);
    });



    //default it should stay at bottom
    app.get('*',function (req, res) {
        //res.redirect('/');
        res.send(404);
    });
}

console.log on dbfn file writes full object from mysql databse but when I call it on routes.js file as var x it null I really dont understands how actually I can overcome with that. Yes, I am new student to NodeJs

Thanks.



via Vishal Patel

No comments:

Post a Comment