-
항해 99 5기 TIL_15항해 99 2022. 1. 25. 01:02
▶ Today I Learned
<Query string>
: 웹 주소창에 입력된 파라미터 값(문자열), 주로 key: value 형태로 이루어져 있으며
여러 개를 동시에 쓸 경우 &(앰퍼샌드)로 이어줄 수 있음
장점: URL상의 정보를 바꾸어 줌으로써 간단히 페이지를 넘길 수 있다
단점: 데이터의 길이에 제약이 있으며 정보가 그대로 노출되기 때문에 보안을 유지해야하는 데이터를 쓸 수 없다.
또한 특수문자를 이 방식으로 보낼 때는 URLencoded 메서드를 사용하여야 한다.
<Node.js 홈페이지 구현 - 장바구니 수정 API>
/* 상품 수정 API */ // 일부가 아닌 모든 데이터 업데이트 시 put 사용 // 동일한 리소스에 대해서는 동일한 주소 사용 router.put("/goods/:goodsId/cart", async(req, res) => { const {goodsId} = req.params; const {quantity} = req.body; // body는 json데이터를 넘겨받기 때문에 type까지 같이 받을 수 있음 const existsCarts = await Cart.find({ goodsId: Number(goodsId) }) // existsCarts는 배열로 반환됨 if (!existsCarts.length) { // 담으려는 제품의 goodsId가 장바구니 내 제품에 없다면 장바구니 추가, 있다면 값 업데이트 await Cart.create({goodsId: Number(goodsId), quantity}); // 장바구니 추가 기능까지 put으로 통합 } else { await Cart.updateOne({ goodsId: Number(goodsId) }, { $set: {quantity}}) // MongoDB에서는 위와 같이 set으로 다른 값들을 설정해주기로 약속되어 있음 } res.json({success: true}); })
<Node.js 홈페이지 구현 - 장바구니 목록 조회 API>
/*장바구니 목록 조회*/ router.get ("/goods/cart", async (req,res) => { // 경로는 실제로 /api/goods/cart 라고 볼 수 있다. 서버파일인 app.js에서 express.js의 use 기능을 통해 // 지정해주었다. const carts = await Cart.find() // DB에서 찾아 조회 // 당연히 이 역시도 await을 붙여주어야 해주어야 한다. 그렇지 않으면 // 카트 내 목록의 정보를 건내줘서 카트 내 goods의 ID값을 아래로 건네주기도 전에 아래 구문들이 실행되어 오류 발생 const goodsIds = carts.map((cart) => cart.goodsId); // 장바구니에 담긴 제품의 아이디들을 배열에 담아 goodsIds에 대입 const goods = await Goods.find({ goodsId: goodsIds }); // 위의 goodsIds에 해당되는 아이디들의 물건들을 찾아 goods에 대입 res.json ({ cart: carts.map((cart) => { return { quantity: cart.quantity, goods: goods.find((item) => item.goodsId === cart.goodsId) // goods의 id 번호와 cart의 id 번호가 같은 goods 반환 } // return을 없이 약식으로 쓰고 싶다면 {} 바깥 부분을 ()로 감싸면 됨, // 그 부분은 값이며 안에 객체가 들어있다고 인식 }) }) });
출처: 스파르타 코딩클럽 Node.js 입문 강의
▶ 느낀 점
위에 적어놓은 것들은 오늘 공부한 것의 일부를 기록한 것이다. 실제로는 더 많은 것들을 공부했으며 오늘도 14시간 정도를 투자했다..
이제 겨우 express.js와 es6의 문법들(module화, require로 import해오기, router), mongoose 라이브러리에 대한 가닥을 조금 잡았다.. 하지만 여전히 배울 것은 많고 당장 홈페이지를 구현해야 하므로 배운 것을 최대한 활용하고 필요한 것을 깊이 조사해보자.
막막할 때도 있지만 즐겁기도 하고 문제를 해결했을 때의 희열감은 이루 말할 수 없다 :)
내일도 화이팅팅..!
▶ 공부 시 참고 링크들
https://www.lainyzine.com/ko/article/git-init-how-to-initialize-git-repository/
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_17 (0) 2022.01.27 항해 99 5기 TIL_16 (0) 2022.01.26 항해 99 5기 WIL_2 (0) 2022.01.23 항해 99 5기 TIL_14 (0) 2022.01.23 항해 99 5기 TIL_13 (0) 2022.01.22