Cart cannot function as a constructor

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!

Answer №1

There is an issue with the way you are handling exports in cart.js. The Cart object is not being properly exported as a function.

To fix this, you have two options:

module.exports = Cart;

...or you can modify the export and import statements like this:

module.exports.Cart = Cart;
// ...and in your other script...
var Cart = require('../lib/cart.js').Cart;
//                                  ^^^^^

Both approaches will work. If Cart is the only thing you want to export, the first option is probably better.

Answer №2

Make sure to include the Cart function in your code.

var shoppingCart = new Cart(req.session.cart ? req.session.cart : { items: {}});

Don't forget to add this line: module.exports = shoppingCart; to your module file myShoppingCart.js

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to create a dynamic <hr /> using Flexbox?

In the midst of working on my application, I managed to achieve a simple layout. However, there is one peculiar requirement that has been eluding me for the past 2 days and now I find myself in need of assistance. Here is the current HTML code I am workin ...

What is the best way to remove text using javascript?

Hey everyone! I am new to coding in javascript and I'm hoping for some help with stripping text. I have a string that is formatted like this: <iframe src="http://embed.videokoo.com/61YVek?client_file_id=390856&width=720&height=480" style=" ...

How to store lengthy JSON strings in SAP ABAP as variables or literals without extensive formatting restrictions

Is there a way to input lengthy JSON data into ABAP as a string literal without the need for excessive line breaks or formatting? Perhaps enclosing the string in a specific template, or utilizing a method similar to JSON.stringify(..) found in other langua ...

Using Node and Express to Serve Multiple Rendered Views in a Single Response

I'm making an AJAX request and I want to receive a JSON response containing multiple partial views that I can use to update different sections of my page. For example: { "searchResults": "<div>Some HTML string</div>", "paginationB ...

What is the best way to transfer a variable from a template to views.py?

Is there a way for me to pass the oobcode value to the postresetusername function in views.py? reset_username.html <script type="text/javascript"> var oobcode; function func(){ oobcode = localStorage.getItem("storageName"); ...

What is the best way to determine if any of the objects in an array contain a "completed" property with a value of false using JavaScript and React?

Is there a way to determine if at least one item in an array of objects has a completed property with a value of false using JavaScript and React? Here is an example array of objects: const items = [ { id: "32", jobs: [ ...

Interactive HTML and PHP form designed to compute and display the result of a straightforward mathematical equation

I'm looking to add a dynamic HTML/php form on my webpage that can solve the following formula instantly without any page refresh. I am confused about the best approach and the code required to make it happen. The formula I want to implement is as fol ...

Cannon.JS ensures that walls are impenetrable

I am currently experimenting with three.js and cannon.js, but I have encountered an issue where I am unable to create solid walls or any stationary objects that can block the player's movement. Below is the code I have been working on so far. I would ...

Tips for incorporating an userbar into a jade template

Currently, I am trying to figure out how to incorporate a userbar into my jade layout. Here's what my layout.jade looks like: doctype 5 html head title= title link(rel='stylesheet', href='/stylesheets/style.css') body ...

What would the equivalent Javascript implementation look like for this Python code that decodes a hex string and then encodes it to base64?

Currently, I am facing the challenge of transferring code from a Python script that decodes and encodes a string using a series of decode() and encode() functions. In Python, the code appears as follows: import codecs input = '3E061F00000E10FE' ...

What is the best way to use jQuery to increment the number in an input field by a specific value?

My goal is to utilize jQuery to increment a number in an input field and then display the updated value in the same input field. The specific id of this input field is "total". Here's my attempt so far: function addBag(){ var bagprice = 79.99; ...

JavaScript error caused by incorrect JSON parsing

Encountering Another Issue. Here's the Relevant Code: if(localStorage.getItem("temporaryArray")){ var temporaryArray = JSON.parse(localStorage.getItem("temporaryArray")); }else{ var temporaryArray = []; } Essentially, what this code snippet ...

Switching from a GET request to a POST request redirects the user to logout in Node/Express

I am utilizing Stormpath for Expressjs (without Passport currently) to manage my user registration. I am particularly interested in determining the correct method for logging out a user. Previously, I typically used the GET method for logout, but Stormpat ...

Error: Unsupported Media Type when attempting to send JSON data from an AngularJS frontend to a Spring controller

Below is the controller function code snippet @RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"}) public @ResponseBody String logInCheckerFn(@RequestBody UserLogData userLogData){ Integer user ...

Using Javascript to navigate links in a list using keyboard arrow keys

When links are not wrapped in other elements, I am able to change focus easily. Here is how it works: HTML <a id="first" href="#" class='move'>Link</a> <a href="#" class='move'>Link</a> <a href="#" class=&a ...

`The universal functionality of body background blur is inconsistent and needs improvement.`

I've developed a modal that blurs the background when the modal window is opened. It's functioning flawlessly with one set of HTML codes, but encountering issues with another set of HTML codes (which seems odd considering the identical CSS and Ja ...

Step-by-step guide for deploying an Express NodeJS project on a Centos server

I am currently facing a challenge with deploying my NodeJS application, as it is something I have never done before. However, I have successfully completed an Express NodeJS application that utilizes MongoDB as its database. During the development of the ...

Zero-length in Nightmare.js screenshot buffer: an eerie sight

I'm currently working on a nightmare.js script that aims to capture screenshots of multiple elements on a given web page. The initial element is successfully captured, but any subsequent elements below the visible viewport are being captured with a l ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...