Hey all. I have an express app running on the App Platform connected to a MySQL database. I’ve written a simplified code snippet to show my problem.

When a user submits the form this route below will run. It connects to my database and then disconnects (to show the problem). This tends to work perfectly fine the first time but then if the user closes the tab and opens the site again, or they go back to the previous page and submit the form again then I tend to get this error: “upstream connect error or disconnect/reset before headers. reset reason: connection termination”.

const con = mysql.createConnection({
  host: "****",
  user: "****",
  port: ****,
  password: "****",
  database: "****",
  ssl: {
    ca: fs.readFileSync(__dirname + '/public/ca-certificate.crt.txt'),
    rejectUnauthorized: false
  }
});

app.post('/', function (req, res) {
  con.connect(function (err) {
    if (err) throw err;
    con.end();
    res.send("Connected!");
  });

How do I fix this? I know it’s not necessarily something a user would do, but I want to fix it. I think I’m just misunderstanding something.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
1 answer

Hello, thanks for using DigitalOcean App Platform.

I believe once a connection has been terminated using end() a new connection has to be created and established using mysql.createConnection(). Additionally since end() is called in a request handler we should provide a callback to it to handle any potential errors and ensure it completes before we send the response using res.send(). I would suggest reusing the connection for the lifetime of the application, and perhaps utilizing connection pooling.

Submit an Answer