Node js mysql query gives error when executed second time

1.3k views Asked by At

I am trying to make a REST api in node using express. When i open the url in browser the first time, it runs fine and gives me the correct output. But when I hit the api url the second time, the app crashes with the error :

events.js:141 throw er; // Unhandled 'error' event ^

Error: Cannot enqueue Handshake after invoking quit.

This is the code I'm using :

var express = require('express');
var mysql = require('mysql');

var app = express();
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'USER_NAME',
  password: 'PASSWORD'
});

app.use(express.static(__dirname + '/public'));
var port = 3333;

app.get('/api/users/:user_id', function(req, res){
    var lead_id = req.params.user_id;

    connection.connect();

    connection.query('use DB_NAME;', function (err) {
        if(err) throw err;

        connection.query('select * from users where user_id = ' + user_id, function (err, rows) {
            if(err) throw err;

            res.json(rows);
            connection.end();
        });
    });
});

app.listen(port);
console.log("The app is running on port " + port);

Can someone tell me what am I doing wrong ?

2

There are 2 answers

0
Andy On

Try this to remove the redudant connection. This was the first result of a google search of the error message - always try to google error messages before asking SO.

0
Shreyash S Sarnayak On

Just remove connection.connect() and connection.end(). Then it should work.

connection.connect() should be called once or none. Because connection.query will connect I'd it not connected.

PS - connection.connect() need to be called when the connection is lost.