You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js无法将express的app对象传入UpComing类,报错app is not defined

错误原因
  • 类方法内访问实例属性未加this前缀

在APIUpComingModels.js的Get方法中,你直接使用app和mysqlConnection变量,这两个变量并没有在当前作用域定义,你在构造函数中已经将传入的实例挂载到this上,必须通过this.app、this.mysqlConnection才能访问到对应实例。

  • 主文件未创建mysqlConnection实例就直接传入

主文件中仅引入了mysql模块,没有创建数据库连接实例,直接传mysqlConnection也会触发未定义错误。

修复后代码

主文件

const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');

app.use(bodyparser.json());       
app.listen(3000, () => console.log('Express server is runnig at port no : 3000'));

// 新增:创建mysql连接实例,替换为你自己的数据库配置
const mysqlConnection = mysql.createConnection({
  host: 'localhost',
  user: '数据库用户名',
  password: '数据库密码',
  database: '你的数据库名称'
});
// 可选:连接校验
mysqlConnection.connect(err => {
  if(err) console.log('数据库连接失败:', err);
  else console.log('数据库连接成功');
})
    
var UpComing = require('./Api/APIUpComingModels');
const Obj = new UpComing(app , mysqlConnection);
Obj.Get();

APIUpComingModels.js

class UpComing {

    constructor(app , mysqlConnection) {
        this.app = app;
        this.mysqlConnection = mysqlConnection;
    }

    Get(){
        // 修复:通过this访问实例挂载的属性
        this.app.get('/employeees', (req, res) => {
            this.mysqlConnection.query('SELECT * FROM Employee', (err, rows, fields) => {
                if (!err)
                    res.send(rows);
                else
                    console.log(err);
            })
        });
    }
}
module.exports = UpComing

内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:48:01