Kit
Kit

Reputation: 283

TypeError: Cannot read property 'query' of undefined?

I am trying to deploy my node app with Docker.Here is my node app:

var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');
var mongoose =require('mongoose');
app.use(express.static("./app"));

var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'node_db'
});

app.set('port',8080);
app.set('views',path.join(__dirname,'views'));
app.set('view engine','jade');
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyparser.urlencoded({ extended: false }));

app.get('/', function (req, res) {
   res.sendfile('app/index.html');
});

app.get('/getAllBlogs', function (req, res) {
   pool.getConnection(function (err, connection) {
       var sql = mysql.format("select * from blogs");

           connection.query(sql, function (error, results, fields) {
           connection.release();
              if (error) {
                res.send(error);
              }
             res.send(results);
            });
        });
     });

 app.get('/getBlog/:id', function(req,res){ 
 console.log(req.params.id);
 pool.getConnection(function (err, connection) {
    var sql = mysql.format("select * from blogs where id=?", [req.params.id]);
    connection.query(sql, function (error, results, fields) {
        connection.release();
        if (error) {
            res.status(200).send(error);
        }
        res.send(results[0])
    });
  });
});

app.listen(app.get('port'));
console.log('~~Server Runnign on port localhost:'+app.get('port')+'~~');

Here is my Docker file:

FROM node:boron

# Create app directory
RUN mkdir -p /home/sameera/Desktop/test/app
WORKDIR /home/sameera/Desktop/test/app

# Install app dependencies


COPY package.json /home/sameera/Desktop/test/app
RUN npm install

# Bundle app source
COPY . /home/sameera/Desktop/test/app

EXPOSE 8080
CMD [ "npm", "start" ]

The docker file built successfully and when i run below command it is running properly.

docker run -p 49160:8080 img

But when i try to load a page with data that is using mysql it is giving an error:

    connection.query(sql, function (error, results, fields) {
              ^
    TypeError: Cannot read property 'query' of undefined
}

I guess the problem is with that i can't connect to mysql with this container since i am not install or use any mysql related commands in docker file.When i remove all my sql connection and related code it is not giving any error and running properly.I am using ubuntu 14.04

Upvotes: 0

Views: 15153

Answers (2)

Vinod S Pattar
Vinod S Pattar

Reputation: 91

You are using pooling to connect to MySQL and querying with connection.

Use pool for querying:

var mysql = require('mysql'); 

var pool = mysql.createPool({ connectionLimit : 10, host : 'example.org', user : 'bob', password : 'secret', database : 'my_db' }); 

pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); });

Upvotes: 0

Shubham Verma
Shubham Verma

Reputation: 9961

You can use below code if pool is not required:

var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
app.use(express.static("./app"));

var pool = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'node_db'
});
pool.connect();
app.set('port', 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyparser.urlencoded({ extended: false }));

app.get('/test', function (req, res) {
        var sql = mysql.format("SELECT * FROM users");
        pool.query(sql, function (error, results, fields) {
            if (error) {
                res.send(error);
            }
            res.send(results);
             pool.end();
        });
});

app.listen(app.get('port'));
console.log('Server Runnign on port localhost:' + app.get('port'));

Result will be something like that:

[
    {
        "id": 1,
        "firstName": "shubham",
        "lastName": "verma",
        "userName": "shubham",
        "email": "[email protected]",
        "password": "25d55ad283aa400af464c76d713c07ad",
        "sessionId": "bdfb43ae-ee9e-4819-b35a-3cb254885023",
        "isLive": 1,
        "date": "2017-05-06T06:05:24.000Z"
    }
]

But if the pool is necessary and you want to use pool then you should try below code:

var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
app.use(express.static("./app"));

var pool = mysql.createPool({
    connectionLimit: 10,
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'node_db'
});

app.set('port', 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyparser.urlencoded({ extended: false }));

app.get('/test', function (req, res) {
    pool.getConnection(function (err, connection) {
        var sql = mysql.format("SELECT * FROM users");
        connection.query(sql, function (error, results, fields) {
            if (error) {
                res.send(error);
            }
            res.send(results);
            connection.release();
        });
    });
});

app.listen(app.get('port'));
console.log('Server Runnign on port localhost:' + app.get('port'));

Result wll be like that:

[
    {
        "id": 1,
        "firstName": "shubham",
        "lastName": "verma",
        "userName": "shubham",
        "email": "[email protected]",
        "password": "25d55ad283aa400af464c76d713c07ad",
        "sessionId": "bdfb43ae-ee9e-4819-b35a-3cb254885023",
        "isLive": 1,
        "date": "2017-05-06T06:05:24.000Z"
    }
]

Upvotes: 0

Related Questions