无法读取未定义的属性“查询”-MySQL NodeJS

时间:2018-12-27 16:55:53

标签: mysql node.js

当我尝试向节点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);

和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!")
        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。有人可以帮我解决错误吗?

预先感谢, 米歇尔。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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并删除脚本末尾的陷阱

答案 2 :(得分:0)

connection.connect()返回void(check the sources);因此req.dbConnection设置为undefined。
您必须等待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();
  }
})

我认为您必须一次创建连接,而不是每次请求都创建一次。