I need to change port to 54023 for it to run on the right port.
**when i print out quiz after trying to pull data, it is empty.
**
db.connect() is not logging any message.
pg library is correctly installed.
I used pgAdmin 4, the Database is named ‘world’. The Table is named ‘capitals’
console.log("query excuted");
is not printed nor did console.log("hi");
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const db = new pg.Client({
user: "postgres",
host: "localhost",
database: "world",
password: "****",
port: 54023,
});
const app = express();
const port = 3000;
db.connect()
.then(() => console.log('Connected to the database'))
.catch(err => console.error('Failed to connect to the database:', err));
let quiz = [];
console.log('About to execute query');
db.query("SELECT * FROM capitals", (err, res) => {
if (err) {
console.error("Error executing query", err.stack);
console.log("hi");
} else {
console.log("query excuted");
quiz = res.rows;
console.log(quiz);
}
db.end();
});
let totalCorrect = 0;
console.log(quiz);
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
let currentQuestion = {};
// GET home page
app.get("/", (req, res) => {
totalCorrect = 0;
nextQuestion();
console.log(currentQuestion);
res.render("index.ejs", { question: currentQuestion });
});
// POST a new post
app.post("/submit", (req, res) => {
let answer = req.body.answer.trim();
let isCorrect = false;
if (currentQuestion.capital.toLowerCase() === answer.toLowerCase()) {
totalCorrect++;
console.log(totalCorrect);
isCorrect = true;
}
nextQuestion();
res.render("index.ejs", {
question: currentQuestion,
wasCorrect: isCorrect,
totalScore: totalCorrect,
});
});
function nextQuestion() {
const randomCountry = quiz[Math.floor(Math.random() * quiz.length)];
currentQuestion = randomCountry;
console.log(currentQuestion);
}
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Well the error initially started with incorrect port number, which i changed. Then the error tells me the question, which is passed on by app.get, does not existed. Then, i looked at the quiz – it turns out it did not pull the database correctly. It is empty. So i look into db.query, it looks like it is not executing each of the lines. Then i look at db.connect(), nothing is printing either?