i am trying to pass cart products to a checkout but whenever i click on place order i'm redirected to the checkout page yes but the cart items do not appear there and the terminal says: Cart data in session: undefined
listCarts: []
here is my add to cart funtion in my server file:
// Add-to-cart route
app.post('/add-to-cart', function (req, res) {
const { productId, quantity } = req.body;
console.log('Adding to cart - Product ID:', productId, 'Quantity:', quantity);
const productDetails = getProductDetailsFromMenu(productId);
console.log('Product Details:', productDetails);
if (productDetails) {
req.session.cart = req.session.cart || [];
console.log('Existing Cart:', req.session.cart);
const existingItem = req.session.cart.find(item => item.productId === productId);
if (existingItem) {
existingItem.quantity += quantity;
} else {
req.session.cart.push({
productId: productId,
name: productDetails.name,
basePrice: productDetails.basePrice,
price: productDetails.basePrice * quantity,
quantity: quantity,
image: productDetails.image,
});
}
console.log('Updated Cart:', req.session.cart);
// Redirect to the homepage or menu page
res.redirect('/menu');
} else {
res.status(404).send('Product not found');
}
});
What I have tried:
i have tried adding the following lines of codes to my checkout script:
<div class="col-md-12 col-lg-12">
<div class="odr-box">
<div class="title-left">
<h3>Shopping cart</h3>
</div>
<div class="rounded p-2 bg-light">
<% if (listCarts && listCarts.length > 0) { %>
<% listCarts.forEach(item => { %>
<div class="media mb-2 border-bottom">
<div class="media-body">
<a href="detail.html"><%= item.name %></a>
<div class="small text-muted">
Price: $<%= item.basePrice.toLocaleString() %>
| Qty: <%= item.quantity %>
| Subtotal: $<%= item.price.toLocaleString() %>
</div>
</div>
</div>
<% }); %>
<% } else { %>
<p>No items in the cart</p>
<% } %>
</div>
</div>
</div>
// Retrieve cartData from localStorage
const cartData = localStorage.getItem('cartData');
const listCarts = JSON.parse(decodeURIComponent(cartData));
console.log(listCarts);