Node.js

인프런 - shoppingCart - 4

오쟝 2023. 12. 19. 12:10

cookie를 사용해서 cart에 cookie 값을 넣어보자!

app.get('/cart', function(req, res){
    // cart의 쿠키값 전달
    var cart = req.signedCookies.cart
    if(!cart){
        res.send('EMPTY!')
    }
    else {
        var output = ''
        for(var id in cart){
            // id는 제품의 id값
            output += `<li>${products[id].title} (${cart[id]})</li>`
        }
        res.send(`<h1>CART</h1><ul>${output}</ul><a href="/products">Products List</a>`)
    }
})

 

cart에 cart cookie의 값을 전달해줍니다

만약 cart cookie에 값이 없다면 EMPTY를 브라우저에 전달합니다.

값이 존재하면 for ~ in문을 사용하여 cart에 있는 값을 id를 통 가져옵니다.

cart products
{ '1': 7, '2': 4, '3': 5 } {
  '1': { title: 'Goods1' },
  '2': { title: 'Goods2' },
  '3': { title: 'Goods3' }
}

 

cart는 ` id : cart[id] ` 형태로 저장이 되어있고,

products ` name : { products[name] : products[name].title } ` 형태로 저장되어 있습니다. 

 

따라서 for ~ in문을 순회하고 나면 output에 ` <li> ~ Goods1 (7) ~ </lit> ` 과 같이 저장이 됩니다!

이를 cart에 전송해주면 

이런 결과가 나옵니다!

 

app.use(cookieParser('dfad&fke(66%&4'))

 

처음 쿠키를 사용할 때 cookieParser()에 문자를 넣어주면 문자가 key값이 됩니다! 이를 통해 쿠키를 암호화 할 수 있습니다!

'Node.js' 카테고리의 다른 글

인프런 - Login - 2  (0) 2023.12.21
인프런 - Login - 1  (0) 2023.12.21
인프런 - shoppingCart - 3  (0) 2023.12.19
인프런 - shoppingCart - 2  (0) 2023.12.19
인프런 - cookie는 뭘까 🧐 - 1  (0) 2023.12.19