`req.body.country`와 `req.body["country"]` 모두 `req.body` 객체 내의 `country` 속성을 참조하는 방법입니다. 그러나 상황에 따라 사용하는 방법이 다를 수 있습니다:
1. **점 표기법 (dot notation)**:
- 사용하기 간편하며, 속성 이름이 유효한 변수 이름 규칙을 따라야 합니다. 즉, 공백이나 특수 문자가 없어야 합니다.
- 예: `req.body.country`
2. **대괄호 표기법 (bracket notation)**:
- 속성 이름이 변수 이름 규칙을 따르지 않거나, 공백이나 특수 문자를 포함하는 경우에도 사용할 수 있습니다.
- 예: `req.body["country"]`
따라서 코드 작성 시 변수 이름의 유효성과 속성 이름의 특수한 경우를 고려하여 선택하시면 됩니다! 😊
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const app = express();
const port = 3000;
const db = new pg.Client({
user:"postgres",
host: "localhost",
database: "world",
password: "password",
port:5432,
});
db.connect();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.get("/", async (req, res) => {
const result = await db.query("SELECT country_code FROM visited_countries");
let countries = [];
result.rows.forEach((country) => {
countries.push(country.country_code);
});
res.render("index.ejs", { countries: countries, total: countries.length });
});
app.post("/add", async (req, res) => {
const input = req.body["country"];
// console.log(input);
try {
const addCountry = await db.query(
"SELECT country_code FROM countries WHERE LOWER(country_name) LIKE '%' || $1 || '%';",
[input.toLowerCase()]
);
const addCode = addCountry.rows[0].country_code;
console.log(addCode);
try {
await db.query(
"INSERT INTO visited_countries (country_code) VALUES ($1)",
[addCode]
);
res.redirect("/");
} catch(err) {
console.log(err);
const result = await db.query("SELECT country_code FROM visited_countries");
let countries = [];
result.rows.forEach((country) => {
countries.push(country.country_code);
});
res.render("index.ejs", {
countries: countries,
total: countries.length,
error: "Country has already been added, try again.",
});
}
} catch(err) { // invalid name
console.log(err);
let countries = [];
const result = await db.query("SELECT country_code FROM visited_countries");
result.rows.forEach((country) => {
countries.push(country.country_code);
});
res.render("index.ejs", {
countries: countries,
total: countries.length,
error: "Country name does not exist, try again.",
});
}
})
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});