Unlike PHP, where the entire app is reloaded for each request, a Node app stays in-memory between requests - this means that every time someone visits the /people route, the app is going to try to create a new DB connection instead of reusing the existing one.
I would create the connection when initializing the app, and only start serving requests if the DB connection is successful:
const express = require('express');
const mysql = require('mysql');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'dbuser',
password: 'password',
database: 'dbname'
});
app.get('/people', (req, res) => {
connection.query("SELECT firstname FROM users", (error, results, fields) => {
res.render('people', {people: results});
});
});
connection.connect((err) => {
if (err) throw err;
app.listen(3000, () => console.log('Example app listening on port 3000!'));
});
// close connection when app is shutdown
process.on('SIGINT', () => connection.end());