I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end.
Here is my cart.js:
// Ensure that the file is required correctly by logging this function to the console.
sayHello = function () {
return "Hello in English";
};
var Cart = function Cart(oldCart) {
this.items = oldCart.items;
this.add = function (item, id) {
var storedItem = this.items[id] = { item: item };
storedItem.qty++
};
this.generateArray = function () {
var arr = [];
for (var id in this.items) {
arr.push(this.items[id]);
}
return arr;
};
};
module.exports;
Next, in my index.js file, I have set up routes to list products, add them to the cart, and display the cart:
// Code snippet from index.js
// Remember to include relevant require statements and configurations
router.get('/', function (req, res) {
console.log(sayHello());
Products.find(function (err, products) {
res.render('index', { title: 'Express 2017 ', products: products });
console.log(products);
});
});
// More route definitions...
router.post('/cart', (function (req, res) {
console.log(sayHello());
var productid = req.body.id
var cart = new Cart(req.session.cart ? req.session.cart : { items: {} });
Products.findById({ _id: productid }, function (err, product) {
console.log(product.name);
if (err) {
return res.redirect('/');
}
cart.add(product, product.id)
req.session.cart = cart;
console.log(request.session.cart)
res.redirect('/');
});
}));
module.exports = router;
Question: Despite everything working well on the home page, when I click on "Add To Cart" button, I encounter an error "Cart is not a constructor". I would appreciate detailed assistance or guidance to help me understand and resolve this issue. Thank you!