Here is my index.js code
var express = require("express");
var mysql = require('mysql');
var pug = require('pug');
var bodyparser = require('body-parser');
var app = express();
var conn = mysql.createConnection({
host: "remotemysql.com",
user: "",
password: "",
database: ""
});
conn.connect(function(err) {
if (err) {
console.log("Error connecting to MySQL:", err);
} else {
console.log("Connection established");
}
});
let people = [];
let i = 0;
let subname = null;
let subemail = null;
let subsession = null;
app.set("views", "views");
app.set("view engine", "pug");
app.use(express.static("public"));
app.use(bodyparser());
app.get("/", function(req, res, next) {
res.render("confirmed");
});
app.post("/register", function(req, res, next) {
var attendees = {
name: req.body.name,
email: req.body.email,
session: req.body.selectpicker
};
conn.query("INSERT INTO attendees SET ?", attendees, function(err, result, ) {
if (err)
res.send(err);
else
res.send("Thank You for registering!");
});
if (i = 0) {
people.pop();
}
subname = req.body.name;
subemail = req.body.email;
subsession = req.body.session;
let locals = {
name: subname,
email: subemail,
session: subsession
};
people.push(subname + "," + subemail + "," + subsession);
console.log(locals);
console.log(subname);
console.log(subemail);
console.log(subsession);
console.log("People: " + people);
res.render("confirmed", locals);
});
//app.post("/register", function(req, res) {
//});
app.get("/list", function(req, res, next) {
let peoplelist = {
attendeelist: people
}
res.render("list", peoplelist);
});
app.listen(3000);
I keep getting the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:526:11) at ServerResponse.header (/home/runner/M18-CloudSecConf-with-DB/node_modules/express/lib/response.js:771:10)
what do i need to change, move, or add to get this to go away. I understand somewhat that it is trying to send data to the server and then can't set the headers but I'm not sure what to do. Please help, trying to learn this stuff.
res.send()andres.render()in the same request handler. You get to send only ONE response per request. Pick one of the other, not both. This particular error is the http engine tell you that you're trying to send the headers for a response, but you've already sent the response. The error would be a bit more helpful if it said: "http response already sent, can't send another one". - jfriend00