我有以下用于连接数据库的模块:
module.exports = {
var sequelize = new Sequelize('db', 'rt', 'pw', {
host: "localhost",
port: 3306,
socketPath: '/var/run/mysqld/mysqld.sock',
dialect: 'mysql'
})
}
然后在主文件中
var configDB = require('./config/database.js');
但不幸的是,这会返回以下错误:
/config/database.js:3
var sequelize = new Sequelize('db', 'rt', 'pw', {
^^^^^^^^^
SyntaxError: Unexpected identifier
at exports.runInThisContext (vm.js:69:16)
at Module._compile (module.js:432:25)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:349:32)
at Function.Module._load (module.js:305:12)
at Module.require (module.js:357:17)
at require (module.js:373:17)
at Object.<anonymous> (/server.js:14:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
我是否错误地使用了exports
功能?导出模块中的每个对象都会发生此错误。
编辑:以下内容返回cannot call method .authenticate of undefined
,即使模块似乎导出没有错误。
configDB.sequelize // connect to our database
.authenticate()
.complete(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
})
答案 0 :(得分:1)
您在对象文字中使用了错误的语法。我不确定你要完成什么(具体来说,你打算如何在你的主文件中使用configDB
?),但你有一些奇怪的对象文字语法和功能语法的混合上。也许你想要的东西如下:
var sequelize = new Sequelize('db', 'rt', 'pw', {
host: "localhost",
port: 3306,
socketPath: '/var/run/mysqld/mysqld.sock',
dialect: 'mysql'
});
module.exports = sequelize;
编辑:
您误解了有关如何在javascript中存储和传递资源的几个基本要素,鉴于您当前的结构,我认为您需要将database.sequelize
替换为configDB
:
var configDB = require('./config/database.js');
configDB
.authenticate()
.complete(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
})