简体   繁体   中英

Node js mysql query gives error when executed second time

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 ?

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.

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.

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