简体   繁体   中英

Node.js server crashes after MySQL connection ends

I have a Node.js server that is hosting my webpage. I have recently set up a MySQL server and created a connection to the server. When accessing a certain page, it queries the SQL database.

My problem is that if I query the DB, it makes the connection just fine, but it will crash a little later when the server automatically closes the connection. I then tried to use con.end() after the query, but this crashes the second I access the DB. It throws the error below:

    at Protocol._validateEnqueue (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:203:16)
    at Protocol._enqueue (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:138:13)
    at Connection.query (/home/pi/Documents/node_modules/mysql/lib/Connection.js:200:25)
    at Handshake.con.connect (/home/pi/Documents/PageDB.js:26:9)
    at Handshake.<anonymous> (/home/pi/Documents/node_modules/mysql/lib/Connection.js:502:10)
    at Handshake._callback (/home/pi/Documents/node_modules/mysql/lib/Connection.js:468:16)
    at Handshake.Sequence.end (/home/pi/Documents/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
    at Handshake.Sequence.OkPacket (/home/pi/Documents/node_modules/mysql/lib/protocol/sequences/Sequence.js:92:8)
    at Protocol._parsePacket (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:278:23)
    at Parser.write (/home/pi/Documents/node_modules/mysql/lib/protocol/Parser.js:76:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
Close the database connection.

It seems to me that this is caused by the query executing after the con.end() runs. Can someone help me figure out a way to call the end function after the callback has returned with the SQL query data? Or otherwise, have my web server not crash when the connection to the DB is closed automatically? I'm open to either one. Thanks!

Code for the Node.js server is below:

//Create a connection to the db
const con = mysql.createConnection({
  host: 'localhost',
  user: 'test',
  password: 'test',
  database: 'test',
});

router.get('/products',(req,res)=>{
  con.connect((err) => {
    if(err){
      console.log('Error relating to connection: ' + err);
      return;
    }
    console.log('Connection established');

    con.query('SELECT * FROM ProductList',(err,rows,fields)=>{
      if(!err)
        res.send(rows);
      else
        console.log(err);
    })
  });
  con.end(function(err) {
  if (err) {
    return console.log('error:' + err.message);
  }
  console.log('Close the database connection.');
  });
});

Your problem is that you're con.end is being called right after you connect method. As JS is asynchronous, so it will not wait for connect to end and then continue to end instead it will call connect and put the callback on the event queue and continue to next statement where you are closing your connection. So, what you should do is move your end statement inside the callback. Try using the following code

//Create a connection to the db
const con = mysql.createConnection({
    host: 'localhost',
    user: 'test',
    password: 'test',
    database: 'test',
});

router.get('/products', (req, res) => {
    con.connect((err) => {
        if (err) {
            console.log('Error relating to connection: ' + err);
            return;
        }
        console.log('Connection established');

        con.query('SELECT * FROM ProductList', (err, rows, fields) => {
            if (!err) {
                res.send(rows);
                con.end(function(err) {
                    if (err) {
                        return console.log('error:' + err.message);
                    }
                    console.log('Close the database connection.');
                });
            } else
                console.log(err);
        })
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM