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

Error message: The function for the AJAX call is not defined

I'm currently working with jQuery's ajax function and encountering an error: 'getQty is not defined' Can you spot my mistake here? jQuery Code: function getQty() { var dataString = "itemId=" +$(".itemId").val(); $.ajax({ t ...

Ajax appends a single row, not an entire array

My ajax function is retrieving an array of data from the backend, but when I try to display it in the blade, only one row appears instead of multiple rows. List of Problems Only 1 row is appended by ajax The select option is empty when the results return, ...

Deploying an Angular application created using Yeoman to Heroku

I have been following some instructions on how to deploy my project, such as this guide or this tutorial. However, I am unable to get it to work properly. This is the code in my server.js file: var app, express, gzippo, morgan; gzippo = require('gz ...

Is it possible for the router to hold off until a promise is fulfilled before proceeding?

After implementing the code snippet provided by express router, an error occurs when trying to use another async function. The specific error message is: Error: Can't set headers after they are sent. Interestingly, upon removing the line await anot ...

Display the webpage exclusively when the application has been set with `app.use('/api')` in Express 4

Here is what I currently have: app.js ... var api = require('./routes/api'); app.use('/', api); app.use('/api', api); ./routes/api ... var router = express.Router(); router.get('/', passport.authenticate(' ...

Can you explain the purpose of req.params in ExpressJS when compared to PHP?

When working with PHP, we are familiar with $GET which is similar to req.query in nodeJS, and $POST which is equivalent to req.body in nodeJS. But how can we access req.params in PHP? For instance, if my request URL is In Node.js, by using a route like ...

Google Chrome is asking for 2 requests instead of 1

We are in the process of constructing a single-page application utilizing vue.js and Node.js with Express. The SPA is sourced from one domain while the REST API is hosted on another. An issue that has arisen is that when making an ajax call to a different ...

What is the reason for Next.js passing static files as parameters in the URL?

Initially, I encountered the following error: Fetch API cannot load file:///xxxx/web-frontend/node_modules/axios/lib/core/createError.js. URL scheme must be "http" or "https" for CORS request. I was puzzled as to why this error occurred. Upon checking th ...

Dropdown menu utilizing processing API and interacting with AJAX and DOM manipulation

My API data is not showing up in the dropdown menu. If I use ?act=showprovince, I can see the result. example.html <head> <link rel="stylesheet" type="text/css" href="css/normalize.css"> <link rel="stylesheet" type="text/css" hr ...

I am having trouble with $(this) in my jQuery click event handler

When I click my function, I want to change a parent element that contains this function. However, $(this) is not working. What could be the issue? function accountConfirm(message, title, yes_label, no_label, callback) { console.log($(this)); $(&qu ...

The function is unable to accurately retrieve the state value

In my app, I have a component where I'm attempting to incorporate infinite scroll functionality based on a tutorial found here. export const MainJobs = () => { const [items, setItems] = useState([]); const [ind, setInd] = useState(1); const ...

Deleting validation messages from my MVC controls

I set up some validation in my Model by adding the following code: [Required] [StringLength(60, MinimumLength = 4)] [Display(Name = "Users code")] public string UserCode { get; set; } When c ...

When using `setState()`, ensure that you are updating a component that is already mounted or in the process of mounting. If you receive this error, it

When using WebSocket to communicate with my server, I call the handleSubmit() function to send data and update my state based on the received response. Everything works fine initially. Upon calling componentWillUnmount, I stop sending data to the websocke ...

Using JavaScript to control a dropdown list based on the selection of another dropdown

Hello, I am new to programming and a JavaScript beginner seeking help from you all. I have two dropdown lists and I am attempting to manipulate one based on the selection of the other using JavaScript. Both dropdown lists contain time in hours denoting st ...

The useSelector from @reduxjs/toolkit in Next.js is returning an undefined value

Utilizing js and @reduxjs/toolkit in my current project has resulted in an issue where the useSelector method is returning undefined values when trying to access data from the store. Below is a snippet of my reducer file: import { createSlice } from "@red ...

Flow error: Unable to access the value of this.props.width as the property width is not defined in T

In my React Native project, I am utilizing Flow for type checking. For more information, visit: I currently have two files named SvgRenderer.js and Cartoon.js where: Cartoon extends SvgRenderer Below is the source code for both of these files: SvgRend ...

Having trouble with JavaScript concat function not behaving as it should? Can you provide more details to

I am trying to extract all the cities from an object that contains country names as keys and arrays of cities as values. However, my approach seems to be failing and I can't figure out why. var cities = { "United Kingdom": ['london'], ...

What steps should I take when dealing with two dynamic variables in a mediator script within the WSO2 ESB?

I'm facing an issue with my if condition - it doesn't work properly when the value is static. However, when I make `annee2` and `annee1` static (for example =2019), it works fine. Here's the code snippet: <script language="js"&g ...

What exactly is the role of HTTP in data flow? Is JSON separate from the HTTP requests?

Let's take a look at this code snippet that demonstrates how to fetch a list of to-dos from an SQLite3 database: First, there is an axios request in the frontend: useEffect(() => { axios.get('http://localhost:3001/todo', {}) .the ...

In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention: Bla = function() { this.prop = 123; } Bla.prototype.yay = function() { console.log(this,this.prop); } X = new Bla(); $(document).ready(X.yay); // output: #document undefined --> why? $(document).ready(functio ...