-
[고농축 백엔드 코스Quiz5]프론트엔드와 API 연동하기 - /starbucks프로젝트/고농축 백엔드 코스 2023. 7. 30. 20:59
FrontEnd
quiz5/backend/frontend/index.html
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="./index.css" /> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="index.js"></script> <script src="menu.js"></script> <title>메뉴</title> </head> <body> <div class="Container"> <div id="Wrapper"> <div id="Navi_Wrapper" style="width: 100%; display: flex; justify-content: space-between" > <a href="../login/index.html" class="Back_Button"> 🔙로그인 </a> <a href="../user/index.html" class="Back_Button"> 유저정보🔜 </a> </div> <div id="Title_Wrapper">나만의 메뉴</div> <div onclick="openMenu()" id="Open_Menu_Btn">메뉴 열기</div> <div class="CloseBtnWrapper"> <span id="CloseBtn" onclick="closeMenu()">X</span> </div> <div id="Menu_Background"></div> </div> </div> </body> </html>
BackEnd
quiz5/backend/index.js
import express from "express"; import swaggerUi from "swagger-ui-express"; import swaggerJSDoc from "swagger-jsdoc"; import { options } from "./swagger/config.js"; import cors from "cors"; const app = express(); // swagger 생성 app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerJSDoc(options))); app.use(express.json()); app.use(cors()); app.get("/starbucks", (req, res) => { const result = [ { name: "카레라이스", kcal: 5 }, { name: "카페라떼", kcal: 5 }, { name: "카푸치노", kcal: 5 }, { name: "바닐라라떼", kcal: 205 }, { name: "딸기라떼", kcal: 335 }, { name: "녹차", kcal: 5 }, { name: "콜드브루", kcal: 5 }, { name: "프라푸치노", kcal: 5 }, { name: "자허블", kcal: 5 }, { name: "슈크림라떼", kcal: 500 }, ]; res.send(result); }); app.listen(3000, () => { console.log("POSTMAN으로 요청을 보냈습니다."); });
quiz5/backend/menu/index.js
const openMenu = () => { console.log("메뉴 열기 버튼 클릭"); // 모달창 열기 let wrapper = document.getElementById("Wrapper"); let menu = document.getElementById("Menu_Background"); let button = document.getElementById("Open_Menu_Btn"); let closeButton = document.getElementById("CloseBtn"); let naviWrapper = document.getElementById("Navi_Wrapper"); let titleWrapper = document.getElementById("Title_Wrapper"); wrapper.style.backgroundImage = "url()"; wrapper.style.backgroundColor = "rgba(0,0,0,0.9)"; button.style.display = "none"; menu.style.display = "flex"; closeButton.style.display = "flex"; naviWrapper.style.display = "none"; titleWrapper.style.display = "none"; // 커피 목록 조회 API 요청 getCoffee(); }; const closeMenu = () => { let wrapper = document.getElementById("Wrapper"); let menu = document.getElementById("Menu_Background"); let button = document.getElementById("Open_Menu_Btn"); let closeButton = document.getElementById("CloseBtn"); let naviWrapper = document.getElementById("Navi_Wrapper"); let titleWrapper = document.getElementById("Title_Wrapper"); while (menu.firstChild) { menu.removeChild(menu.firstChild); } wrapper.style.backgroundImage = "url(../img/menu-back-ground.jpg)"; wrapper.style.backgroundColor = "rgba(0,0,0,0.2)"; wrapper.style.backgroundPosition = "center"; button.style.display = "flex"; menu.style.display = "none"; closeButton.style.display = "none"; naviWrapper.style.display = "flex"; titleWrapper.style.display = "block"; };
quiz5/backend/menu/menu.js
// 커피 목록 조회 API를 요청해주세요. const getCoffee = async () => { console.log("index.js 파일의 openMenu 함수 안에서 getCoffee가 실행 됨"); // 1. 백엔드 서버로 /starbucks API 요청해 커피 데이터를 받는다. const coffeeData = await getCoffeeData(); let coffeeInfo = coffeeData.data; // console.log(coffeeInfo); // 2. 받은 데이터로 createMenuCard 함수를 이용해 메뉴 카드를 모두 만들어주세요. const result = coffeeInfo.map((coffee) => { createMenuCard({ name: coffee.name, kcal: coffee.kcal }); }); }; const createMenuCard = (data) => { const menuCardWrapper = document.createElement("div"); menuCardWrapper.className = "Menu_Card_Wrapper"; const menuCardImgBox = document.createElement("div"); menuCardImgBox.className = "Menu_Card_ImgBox"; const menuCardName = document.createElement("div"); menuCardName.className = "Menu_Card_Name"; menuCardName.textContent = data?.name || "메뉴이름"; const menuCardInfo = document.createElement("div"); menuCardInfo.className = "Menu_Card_Info"; menuCardInfo.textContent = data?.kcal || "칼로리"; const menuWrapper = document.querySelector("#Menu_Background"); menuCardWrapper.appendChild(menuCardImgBox); menuCardWrapper.appendChild(menuCardName); menuCardWrapper.appendChild(menuCardInfo); menuWrapper.appendChild(menuCardWrapper); }; const getCoffeeData = () => { const data = axios.get("http://localhost:3000/starbucks"); return data; };
quiz5/backend/menu/index.css
* { box-sizing: border-box; } .Container { display: flex; justify-content: center; padding: 0 100px; } #Wrapper { width: 640px; height: 100vh; padding: 0 50px; display: flex; flex-direction: column; align-items: center; background-position: center; background-size: cover; background-repeat: no-repeat; background-image: url('../img/menu-back-ground.jpg'); background-color: rgba(0, 0, 0, 0.2); background-blend-mode: multiply; } #Title_Wrapper { padding: 150px 0 50px 0; font-size: 50px; font-weight: bold; color: #fff; } #Menu_Background { overflow: scroll; -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */ margin: 0 0 100px 0; padding: 30px 0; border-radius: 20px; background-color: rgba(999, 999, 999, 0.2); display: none; justify-content: space-evenly; flex-wrap: wrap; width: 100%; } /* Hide scrollbar for Chrome, Safari and Opera */ #Menu_Background::-webkit-scrollbar { display: none; } .Menu_Card_Wrapper { width: 40%; height: 300px; padding: 10px; margin-bottom: 20px; border-radius: 5px; background-color: rgba(999, 999, 999, 0.9); display: flex; flex-direction: column; align-items: center; justify-content: space-evenly; } .Menu_Card_ImgBox { width: 100%; height: 200px; background-color: gray; } .Menu_Card_Name { font-size: 20px; font-weight: bold; } .Menu_Card_Info { font-size: 18px; } #Open_Menu_Btn { background-color: #036635; color: #fff; font-size: 20px; font-weight: bold; border-radius: 10px; padding: 20px; cursor: pointer; } #Open_Menu_Btn:hover { background-color: #fff; color: #036635; } .CloseBtnWrapper { width: 100%; padding-top: 100px; display: flex; justify-content: flex-end; } #CloseBtn { display: none; color: #fff; font-size: 60px; font-weight: bold; cursor: pointer; } #CloseBtn:hover { color: #036635; } .Back_Button { padding-top: 30px; font-size: 30px; font-weight: bold; text-decoration: none; color: #ebebeb; cursor: pointer; } .Back_Button:hover { color: #fff; }
프론트에서 백으로 넘기는데만 이틀을 꼬박 쓴것같다.
get으로 보내고 있던 데이터를 post로 바꾼다음 getCoffeeData()에서 get으로 다시 받아야하는건가?
아니면 frontend단에서 axios를 받아와야하는건가?
axios를 js파일에서 받아오면 ES6 문제로 창이 안열리고..
생각보다 되게 간단한 것들이었는데 '혼자' 힘으로 하려다보니 다 쉽지가 않았다.
1. 프론트엔드에서 axios를 cdn으로 import하고
2. Back에서 새로운 getCoffeeData를 만들어서 (분리) axios.get요청을 통해 데이터를 요청하고
3. 따로 뺀 getCoffeeData를 메인함수에 불러와서
4. createMenuCard()에 데이터를 뿌려주는데 데이터가 길이10의 Array다 보니 Map함수를 사용해서 코드를 줄여줬다. (근데 typeof 사용하면 json으로 받아와서 그런지 Object를 map으로 바꿔주는 과정에서 계속 애를 먹었다.. )
어쨌든 쉬운과제지만 나한텐 너무 어려웠기에 뿌듯
반응형'프로젝트 > 고농축 백엔드 코스' 카테고리의 다른 글
[고농축 백엔드 코스Quiz12]Nest.js 프로젝트 생성 / Starbucks 메뉴 조회 API 만들기 (0) 2023.08.04 [고농축 백엔드 코스Quiz6]프론트엔드와 API 연동하기 - 문자 & 이메일 보내기 (0) 2023.08.01 [고농축 백엔드 코스Quiz5]Rest-API를 GrapQL-API로 변경하기 (0) 2023.07.27 [고농축 백엔드 코스Quiz4] API 명세서 만들기(Swagger) (0) 2023.07.26 [고농축 백엔드 코스Quiz4]Node.js로 회원 목록 조회 API 만들기 (0) 2023.07.26