Node.js - server closed the connection?

后端 未结 1 1692
臣服心动
臣服心动 2021-02-04 16:47

I\'m running a web app on a Node.js server and I need it to be online all the time, so I\'m using forever. But here is what I\'m getting after a period of time:

         


        
1条回答
  •  北海茫月
    2021-02-04 17:25

    The error isn't related to your HTTPS instance, it's related to your MySQL connection.

    The connection to the database is ending unexpectedly and isn't being handled. To fix this, you can use a manual reconnect solution, or you can use connection pooling which automatically handles reconnects.

    Here is the manual reconnect example taken from node-mysql's documentation.

    var db_config = {
      host: 'localhost',
        user: 'root',
        password: '',
        database: 'example'
    };
    
    var connection;
    
    function handleDisconnect() {
      connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                      // the old one cannot be reused.
    
      connection.connect(function(err) {              // The server is either down
        if(err) {                                     // or restarting (takes a while sometimes).
          console.log('error when connecting to db:', err);
          setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
        }                                     // to avoid a hot loop, and to allow our node script to
      });                                     // process asynchronous requests in the meantime.
                                              // If you're also serving http, display a 503 error.
      connection.on('error', function(err) {
        console.log('db error', err);
        if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
          handleDisconnect();                         // lost due to either server restart, or a
        } else {                                      // connnection idle timeout (the wait_timeout
          throw err;                                  // server variable configures this)
        }
      });
    }
    
    handleDisconnect();
    

    0 讨论(0)
提交回复
热议问题