这真的让我很困惑。为什么它不能工作
import express from "express";
import pg from "pg";
const app = express();
const port = 3000;
const db = new pg.Client({
user: "postgres",
host: "localhost",
database: "world",
password: "Pan970628",
port: 5432,
});
db.connect();
let quiz = [];
db.query("SELECT * FROM capitals", (err, res) => {
if (err) {
console.error("Error executing query", err.stack);
} else {
quiz = res.rows;
}
db.end();
});
let totalCorrect = 0;
// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
let currentQuestion = {};
// GET home page
app.get("/", async (req, res) => {
totalCorrect = 0;
await 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,
});
});
async function nextQuestion() {
const randomCountry = quiz[Math.floor(Math.random() * quiz.length)];
currentQuestion = randomCountry;
}
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
这是来自控制台的错误消息,只要知道错误是属性未定义即可。
TypeError:无法读取未定义的属性(读取“toLowerCase”) 在文件:///C:/Users/14577/Desktop/Github/Web-Development-Projects/02%20Back-End/8.0%20PostgreSQL/8.2%20World%20Capital%20Quiz/index.js:48:31
我检查了数据库,完全没问题。并且数据类型是字符串。看起来一切都很好,但就是无法工作。它只是告诉我它未定义。
我仔细检查了我运行的代码。看来我只是想念数据库的字段名称。有一点问题