简体   繁体   中英

node.js/express.js connection pool Cannot read properties of undefined (reading 'getConnection')

So I created a new node.js project and used express.js to build the basics to start of. Now I want to do a simple get call to get data from my database through a connection pool. When I do the call in app.js there is no problem, but when trying to do the same call from my users.js file in a get route it throws 'connection pool Cannot read properties of undefined (reading 'getConnection')'.

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// establish connection to database
var conpool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: '****',
  password: '****',
  database: 'db_name'
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = {app, conpool};

user.js (located in routes directory which is on the same hierarchy level as app.js)

var express = require('express');
var router = express.Router();
var db = require('../app').conpool;

/* GET users listing. */
router.get('/get', function (req, res, next) {
  db.getConnection((err, connection) => {
    if (err) throw err;
    var sql = null;
    if (req.query.name) {
      sql = 'SELECT * FROM users WHERE name = ' + sql.escape(req.query.name);
    } else {
      sql = 'SELECT * FROM users';
    }
    connection.query(sql, function (err, result) {
      if (err) throw err;
      console.log(result);
    });
  });
});

module.exports = router;

Does anyone have any idea why this is happening? Is there something wrong with how I am using module.exports? Is it a problem of trying to call a function on a reference instead of the original pool object?

It seems Evert's solution was the one I was looking for. I'll describe the changes I made compared to the files shown in my question to show how it solved it.

I made a completely new file database.js (on the same level of hierarchy as app.js):

var mysql = require('mysql');

var conpool = mysql.createPool({
    connectionLimit: 10,
    host: 'localhost',
    user: '****',
    password: '****',
    database: 'db_name'
  });

module.exports = conpool;

and deleted all these lines of code from app.js

in user.js only one line changed:

var db = require('../app.js')

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM