无法读取未定义的属性“查询" - MySQL NodeJS [英] Cannot read property 'query' of undefined - MySQL NodeJS

查看:61
本文介绍了无法读取未定义的属性“查询" - MySQL NodeJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I got this type of error when I try to make a post request to my node js server. I link here the error and the two files so you can understand better what I have done.

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

我有两个文件:app.js 和 addReferFriend.js

I got two files: app.js and 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:

and 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.有人可以帮我修复错误吗?

I am using Mysql2. Can somebody help me to fix the error?

提前致谢,米歇尔.

推荐答案

使用这个包:- 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 并删除脚本末尾的捕获

You must control addReferFriend.js and remove a catch in end of script

这篇关于无法读取未定义的属性“查询" - MySQL NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆