프로그래밍/Web

travel tracker 20240325

studylida 2024. 3. 26. 21:00
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"));

// function checkCountry(addCode) {

// }

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);

    var addCode = "";
    const countryList = await db.query("SELECT country_name, country_code FROM countries");
    countryList.rows.forEach((ele) => {
      if(ele.country_name.toUpperCase() === input.toUpperCase()) {
        addCode = ele.country_code;
      } else {
        ;
      }
    })

    if(addCode !== "") {
      await db.query("INSERT INTO visited_countries(country_code) VALUES($1)", [addCode]);
    } else {
      console.log("Invalid country name. Please type correctly.");
    }
    
	res.redirect("/");
})

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

'프로그래밍 > Web' 카테고리의 다른 글

family travel tracker  (0) 2024.03.28
travel tracker 20240326  (2) 2024.03.26
make my own API  (0) 2024.03.14
DIY API  (0) 2024.03.14
axios 예제  (0) 2024.03.13