无法读取未定义的属性“query”-mysql nodejs

ktecyv1j  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(362)

我在尝试向我的节点js服务器发出post请求时遇到了这种类型的错误。我在这里链接错误和两个文件,这样你可以更好地了解我所做的。

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

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

和addreferefriend.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。有人能帮我改正错误吗?
提前谢谢你,米歇尔。

xytpbqjk

xytpbqjk1#

使用此软件包:- 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;

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

44u64gxh2#

这个 app.use('/api/addReferFriend', addReferFriend); 一定是在 app.use(async function(req, res, next) { .. let connection = mysql.createConnection( ... })main.js 因为中间产品是按注册顺序执行的。

xmjla07d

xmjla07d3#

connection.connect() 返回void(检查来源);所以呢 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();
  }
})

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

相关问题