【问题标题】:Cannot read property 'end' of undefined - MySQL , NodeJS无法读取未定义的属性“结束”-MySQL、NodeJS
【发布时间】:2018-12-28 06:51:56
【问题描述】:

我想向您展示我在 NodeJS 和 MySQL 上的错误。 错误在 app.js 的第 45 行

Cannot read property 'end' of undefined
at ServerResponse.<anonymous> (/usr/my_server/app.js:45:24)

当我从“addReferFriend.js”文件中调用请求时会发生这种情况。 我在这里链接了我正在使用的两个文件。

app.js:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql= require('mysql2');
var http = require('http');
var app = express();

var addReferFriend = require('./addReferFriend');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(async function(req, res, next) {
  try {
    if( req.dbConnection ) {
      // ensure that req.dbConnection was not set already by another middleware
      throw new Error('req.dbConnection was already set')
    }

    let connection = mysql.createConnection({
            host: 'xx',
        user: 'xx',
        password: 'xx',
        database: 'xx'
    });

    res.on("finish", function() {
      // end the connection after the resonponse was send
      req.dbConnection.end()
    });

    // wait for the connection and assign it to the request
    req.dbConnection = await connection.connect();
    next();
  } catch(err) {
    next(err);
  }
});

app.use('/api/addReferFriend', addReferFriend);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

module.exports = app;
var server = http.createServer(app);
server.listen(3955);

addReferFriend.js:

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.post('/', function(req, res, next) {
  var uid = req.body.uid;
  var friendReferCode = req.body.friendReferCode;

  var sqlCheckIfExist = "SELECT my_refer FROM hub_user WHERE my_refer = '" + friendReferCode + "'";
  var sqlCodeCheckSameAsMine = "SELECT my_refer FROM hub_user WHERE uid = '" + uid + "'";

  function checkIfUserCodeExist() {
    return req.dbConnection.query(sqlCheckIfExist)
      .then(([rows, fields]) => {
        if (rows == 0) {
          console.log("Non esiste!")

          return res.send(JSON.stringify({
            "status": 500,
            "response": "codeNotExist"
          }));
        }
        console.log("Esiste!")
        return checkIfCodeIsSameAsMine(connection)
      })
  }

  function checkIfCodeIsSameAsMine() {
    return req.dbConnection.query(sqlCodeCheckSameAsMine)
      .then(([rows, fields]) => {
        if (rows == friendReferCode) {
          console.log("Codice uguale!")
          return res.send(JSON.stringify({
            "status": 500,
            "response": "sameCodeAsMine"
          }));
        }
        console.log("Codice non uguale!")
      })
  }

  checkIfUserCodeExist()
   .catch(next)
});
module.exports = router;

我不知道如何解决此类问题。当我调用 checkIfUserCodeExist() 并且它没有加入函数并且直接给出错误时会发生这种情况。我无法打印任何 console.log,因为它坏了。

希望有人可以帮助我解决这个问题。 在此先感谢您的帮助, 米歇尔。

【问题讨论】:

  • return checkIfCodeIsSameAsMine(connection)connection 来自哪里?

标签: node.js


【解决方案1】:

这似乎是req.dbConnection.end() 的问题...对象dbConnection 未定义。

是否有可能由于某种原因首先关闭了连接?所以关闭连接的点不正确?

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 2017-03-06
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2020-10-23
    • 2022-09-23
    相关资源
    最近更新 更多