0

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)
    [...]

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);

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;

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

Thanks in advance, Michele.

1
  • 1
    The app.use('/api/addReferFriend', addReferFriend); has to be after the app.use(async function(req, res, next) { .. let connection = mysql.createConnection( ... }) in the main.js because middlewares are executed the order they are registered. Commented Dec 27, 2018 at 16:58

3 Answers 3

1

use this package: - 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);
});

});`

and replace this code:

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

by this :

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

The app.use('/api/addReferFriend', addReferFriend); has to be after the app.use(async function(req, res, next) { .. let connection = mysql.createConnection( ... }) in the main.js because middlewares are executed the order they are registered.

1 Comment

Editing in this way I got: Cannot read property 'end' of undefined app.js:45:24 here precisely: req.dbConnection.end()
0

connection.connect() returns void (check the sources); so req.dbConnection is set to undefined.
You have to wait the connect event and then bind the connection to req and finally call next.


Otherwise, after a fast reading of mysql2 documentation, you can simplify with this middleware:

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

In my opinion you have to create the connection once and not on every request.

2 Comments

how can i do what you said?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.