title: Node.js MySQL ERR_HTTP_HEADERS_SENT
body: <p>This is the function in question:</p>
  <pre><code>castVote: function (req, res, ip, mysql) {
      // POST return codes
      const ALREADY_VOTED = '100';
      const SUCCESS = '200';
      const FAILURE = '300';
  
      // Create connection to db
      // Keep connection while the client is connected
      var con = mysql.createConnection({
          host: sqlHOST,
          user: sqlUSER,
          password: sqlPASS,
          database: dbNAME
      });
  
      // Connect to db
      con.connect(function (err) {
          // MySQL error, return
          if (err) {
              res.send(FAILURE);
              return;
          }
      });
  
      // Get link voted for
      var link = req.body.song_voted;
  
      // Check if user has already voted
      con.query(`SELECT * FROM VotedUsers WHERE ip = '${ip}'`, function (err, result, fields) {
          if (err) {
              res.send(FAILURE);
              return;
          }
  
          // User hasn't voted
          if (!result.length) {
              // Cast vote here
              // ...
              // Add user's IP to voted list
              con.query(`INSERT INTO VotedUsers (ip) VALUES ('${ip}')`, function (err, result) {
                  if (err) {
                      res.send(FAILURE);
                      return;
                  }
              });
  
              res.send(SUCCESS);
              return;
          }
          // User already voted
          else {
              res.send(ALREADY_VOTED);
              return;
          }
      });
  }
  </code></pre>
  <p>I call the function like this, every time the user clicks a button</p>
  <pre><code>mysql_backend.castVote(req, res, uipv4, mysql);
  </code></pre>
  <p>(<code>mysql</code> is the mysql module. uipv4 is the user's ip).</p>
  <p>Every time I click said button, This is the error output:</p>
  <pre><code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
  </code></pre>
  <p>I've got 2 questions:</p>
  <ol>
  <li>What's wrong with my code?</li>
  <li>Is there a better way of managing a mysql connection for each client (not opening a new one every time the user clicks the button)</li>
  </ol>