1

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 ?

1
  • Consider using a pool instead of a single connection. When you want a connection use pool.getConnection() and when you're done with it use connection.release(); Commented Jan 1, 2017 at 14:50

2 Answers 2

5

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.

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

Comments

0

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.

Comments

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.