mysql node.js/express.js连接池无法读取未定义的属性(阅读“getConnection”)

oyt4ldly  于 2023-01-16  发布在  Mysql
关注(0)|答案(1)|浏览(132)

所以我创建了一个新的node.js项目,并使用express.js来构建基础。现在我想做一个简单的get调用,通过连接池从我的数据库中获取数据。当我在app.js中做调用时,没有问题,但当尝试在get路由中从我的users.js文件做相同的调用时,它会抛出"connection pool Cannot read properties of undefined(reading 'getConnection')"。

    • 应用程序. 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**(位于与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;

有人知道为什么会发生这种情况吗?我使用module.exports的方式有什么问题吗?尝试调用一个引用上的函数而不是原来的池对象有问题吗?

h43kikqp

h43kikqp1#

看来Evert's解决方案是我一直在寻找的解决方案。我将描述我所做的更改,并与问题中显示的文件进行比较,以显示它是如何解决问题的。
我创建了一个全新的文件database.js(与app.js处于同一层次):

var mysql = require('mysql');

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

module.exports = conpool;

并且删除了所有这些行代码app.js
user.js中,仅更改了一行:

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

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

相关问题