首页 > 解决方案 > Node.js、Express 和 MySQL。要求未定义

问题描述

我在我的一个项目中使用 node.js、express 和 mysql,但是当我调用 mysql 时,它向我显示一个错误,告诉我“[Error] ReferenceError: Can't find variable: require”。

//server.js

class SQL{
  constructor(){
    var mysql = require('mysql');
    this.connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : '',
      database : 'newDB'
    });
  }
  connect(){
    this.connection.connect(function(err) {
      if (err) {
        console.error('error connecting: ' + err.stack);
        return;
      }
      console.log('Connected');
    });
  }
  disconnect(){
    this.connection.end(function(err) {
      if (err) {
        console.error('error ending connection: ' + err.stack);
        return;
      }
      console.log('Connection ended');
    });
  }
}


// main.js 

function main(){
  var database = new SQL();
}

main();

在安装 express 之前它工作正常,但在我安装 express 之后它显示错误。

类和函数位于不同的文件中。

标签: mysqlnode.jsexpress

解决方案


推荐阅读