【问题标题】:Cannot read property 'query' of undefined - MySQL NodeJS无法读取未定义的属性“查询” - MySQL NodeJS
【发布时间】:2018-12-27 16:55:53
【问题描述】:

当我尝试向我的节点 js 服务器发出发布请求时,我遇到了这种类型的错误。 我在此处链接错误和两个文件,以便您更好地理解我所做的。

TypeError: Cannot read property 'query' of undefined
    at checkIfUserCodeExist (/usr/my_server/addReferFriend.js:13:29)
    [...]

我有两个文件: app.js 和 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);

并添加ReferFriend.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!")
        console.log(rows[0].my_refer);
        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;

我正在使用 Mysql2。有人可以帮我解决错误吗?

提前致谢, 米歇尔。

【问题讨论】:

  • app.use('/api/addReferFriend', addReferFriend); 必须在main.js 中的app.use(async function(req, res, next) { .. let connection = mysql.createConnection( ... }) 之后,因为中间件按照它们注册的顺序执行。

标签: mysql node.js


【解决方案1】:

使用这个包: - const mysql = require('mysql2/promise');

`app.use(async function (req, res, next) {
if (req.dbConnection) {
    next();
}
mysql.createConnection({
    host: 'xx',
    user: 'xx',
    password: 'xx',
    database: 'xx'
}).then((conn) => {
    req.dbConnection = conn;
    next();
}).catch((error) => {
    next(error);
});

});`

并替换此代码:

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

通过这个:

app.listen(3955, () => {
    console.log("Server listening on port : " + 3955);
});
module.exports = app;

您必须控制 addReferFriend.js 并删除脚本末尾的 catch

【讨论】:

    【解决方案2】:

    app.use('/api/addReferFriend', addReferFriend); 必须main.js 中的app.use(async function(req, res, next) { .. let connection = mysql.createConnection( ... }) 之后,因为中间件按照它们注册的顺序执行。

    【讨论】:

    • 以这种方式编辑我得到:无法准确读取未定义 app.js:45:24 的属性“结束”:req.dbConnection.end()
    【解决方案3】:

    connection.connect() 返回 void (check the sources);所以req.dbConnection 设置为未定义。
    您必须等待connect 事件,然后将连接绑定到req,最后调用next


    否则,在快速阅读mysql2 文档后,您可以使用此中间件进行简化:

    app.use(function(req, res, next) {
      if (req.dbConnection) {
        next();
      }
      else {
        req.dbConnection = mysql.createConnection({
          host: 'xx',
          user: 'xx',
          password: 'xx',
          database: 'xx'
        });
        next();
      }
    })
    

    在我看来,您必须创建一次连接,而不是每次请求。

    【讨论】:

    猜你喜欢
    • 2021-09-12
    • 2020-10-23
    • 2019-11-21
    • 2016-01-07
    • 1970-01-01
    • 2023-03-16
    • 2017-12-13
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多