4

I'm trying to do post request, and it is very successful when I do it with postman, but I'm trying to send it from my client-side. I want to post the cart, but as a result I'm constantly posting item with quantity of 1 no matter of fact how many times do I post that request. What is the best solution to fix this and post the request on the normal way?

  • I'm using session, maybe that would cause the problem sending request from frontend?

This is my post request:

app.post("/add-to-cart/:id", async (req, res) => {
  try {
      const id = req.params.id;
      
      const { data }  = await axios.get("http://localhost:4200/products");
      const singleProduct = await data.find((product) => product._id === id);

    let cart;
    if (!req.session.cart) {
      req.session.cart = cart = new Cart({});
    } else {
      
      cart = new Cart(req.session.cart);
    }
    req.session.cart = cart;
    cart.addProduct(singleProduct);
    console.log(req.session.cart)
    res.send(cart);
    
  } catch (error) {
    console.log(error);
  }
});

This is the Cart code:

module.exports = function Cart(oldCart) {
  this.productItems = oldCart.productItems || {};
  this.totalQty = oldCart.totalQty || 0;
  this.totalPrice = oldCart.totalPrice || 0.00;

  this.addProduct = function(item) {
    let storedItem = this.productItems;
    if (!storedItem.hasOwnProperty("item")) {
      storedItem = this.productItems = {item: item, qty: 1, price: item.price};
      this.totalQty = 1;
      this.totalPrice = item.price;
    } else {
      storedItem = {item: item, qty: storedItem.qty, price: storedItem.price};
      console.log("STORED ITEM: ", storedItem);
      this.productItems = storedItem;
      storedItem.qty++;
      storedItem.price = storedItem.item.price * storedItem.qty;
      this.totalQty++;
      this.totalPrice += storedItem.item.price;
    }
  }
}

This is the function which I put on my button with @click.prevent="addToCart()"

addToCart(){
      let productId = this.oneProduct.id;
      Cart.postCart(productId);
    }

I'm sending this from axios service on frontend:

postCart(productId){
        return cartService.post(`/add-to-cart/${productId}`);
    }

There are no warnings or errors when I try to interact with this on client side. This is the output which I get in my backend (constantly repeating the information of a single product nevertheless this works normally on the client side):

enter image description here

Jan Tuđan
  • 233
  • 3
  • 17
  • Could you put your current `Cart` code in the question too? – theusaf Sep 01 '21 at 14:39
  • Sure, I updated it in my question right now. – Jan Tuđan Sep 01 '21 at 15:33
  • @theusaf do you know how to solve this btw? – Jan Tuđan Sep 01 '21 at 22:44
  • its hard to solve this, as there isn't any examples of what the current output is, and what your expected output is – theusaf Sep 02 '21 at 01:25
  • I'm sorry for that, I updated the image of output of the `console.log` when I try to interact with the data on frontend everything is clean, but the server side shows always the same quantity and the price, behaving as if the session did not exist. My expected output is normal behaviour in console with increasing of the quantity by 1, like when I just test it with postman (just on the server side). Because currently I'm not outputting anything, because the data does not rotate properly. – Jan Tuđan Sep 02 '21 at 10:37
  • Does this only happen with your front end, or does it also happen in postman? – theusaf Sep 02 '21 at 14:38
  • It happens only when I test it on frontend, in postman it works fine. – Jan Tuđan Sep 02 '21 at 15:08
  • I updated my question again, to show my function which is triggered when I click on the button. – Jan Tuđan Sep 02 '21 at 15:24
  • @theusaf did you figure out anything? I bountied a question, so if you solve it you will be rewarded. – Jan Tuđan Sep 03 '21 at 22:43
  • Unfortunately, I haven't figured anything out. It might have something to do with cookies? – theusaf Sep 04 '21 at 14:17
  • I'm not familiar with knowledge of cookies, but I haven't used them at all. – Jan Tuđan Sep 04 '21 at 14:40
  • Hi could you try `return cartService.post(\`/add-to-cart/${productId}\`, { withCredentials: true });` and let me know if that works for you? – Mythos Sep 06 '21 at 10:03
  • its very hard to figure out the error with the bits you posted. I'm having a hard time to understand which code is Node backend and which code is frontend. – Flame Sep 07 '21 at 12:46
  • I think there's a problem at this line: req.session.cart = cart = new Cart({}); you should change it to cart = new Cart({}); – Thinhbk Sep 09 '21 at 04:35

3 Answers3

2

if you are using frontend framework either angular,vue,react or anything that supports routing. you don't need to use res.redirect to change route and get the data.

how about you use res.send(cart) to return the cart data and do the rerouting in the frontend.

async postCart(productId){
    cartService.post(`/add-to-cart/${productId}`);
    // history.push('/your-next-route')
}
Jasper Bernales
  • 1,601
  • 1
  • 11
  • 16
  • This seems fine, but I'm still getting quantity of 1 from frontend whole the time. – Jan Tuđan Sep 01 '21 at 00:33
  • I'm just passing that id, but still don't know why I'm not properly posting data from frontend, my `console.log` is displaying but it shows me the same data, it should me dynamic because I'm stacking data in `req.session` – Jan Tuđan Sep 01 '21 at 00:37
2

I think there's a problem at this line:

req.session.cart = cart = new Cart({});

The reason this assignment does not work as expected is explained here: Multiple left-hand assignment with JavaScript

you should change it to:

cart = new Cart({}); 

The rest of logic should work.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Thinhbk
  • 2,194
  • 1
  • 23
  • 34
0

like your seesionId is't sent to backend, are you using fetch or axios?

fetch:

fetch('https://example.com', {
  credentials: 'include'
})

axios:

{withCredentials: true}

Maybe the server and client are cross-domain? Set the appropriate value of samesite, see this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

yuhengshen
  • 91
  • 3