为什么显示未定义连接?

用户3.14

我正在尝试connectionconnection.js文件使用,并在使用object的其他文件webFrontend.js中使用它exports现在我在运行服务器上得到的是:

{
  "Result": "undefinedThis is result"
}

那意味着connection没有定义。为什么会这样呢?connection如果getConnection在同一(webFrontend.js)文件中创建,则工作正常,但问题是当我getConnectionconnection.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();
};
丹·纳格尔(Dan Nagle)

不需要.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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章