我正在尝试使用 connection.js 文件中的 connection
并使用 在不同的文件 webFrontend.js 中使用它导出
对象。现在我在运行服务器上得到的是:
{
"Result": "undefinedThis is result"
}
这意味着连接
未定义。为什么会发生这种情况?如果在同一个 (webFrontend.js) 文件中创建 getConnection
,则 connection
工作正常,但问题是当我使用 getConnection
在 connection.js 中的相同导出函数中,因此 connection
未定义错误:
这里有 2 个必要的文件(路由文件没有问题),它们解释了我正在做的事情:
connection.js
var mysql = require('mysql');
exports.connExport = function () {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
if(connectionPool) {
connectionPool.getConnection(function (err, connection) {
if (err) {
return err;
} else {
return connection;
}
});
}else{
var abc="return error";
return abc;
}
}
webFrontend.js
var connObj=require('../Routes/connection.js');
var connection=connObj.connExport();
exports.getIndivRecords= function(req, res, next){
res.send({
Result: connection+"This is result"
});
return next();
};
最佳答案
无需 .js
文件扩展名,它会自动为您添加。
下面的代码使用标准错误优先回调
webFrontend.js
var connection = require('../Routes/connection');
exports.getIndivRecords = function(req, res, next){
// connection takes a standard error-first callback
connection(function(err, conn){
if (err) {
// Handle the error returned
console.log(err);
}
// The database connection is available here as conn
console.log( "Connection:" + conn);
// presumably you want to do something here
// before sending the response
res.send({
Result: conn + "This is result"
});
});
return next();
};
connection.js
var mySQL = require('mysql');
var connectionPool = mySQL.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
var getConnection = function (cb) {
connectionPool.getConnection(function (err, connection) {
// pass the error to the callback
if (err) {
return cb(err);
}
cb(null, connection);
});
};
module.exports = getConnection;
关于javascript - 为什么显示连接未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40501764/