Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
Trying to send data from client side but req.session doesn't work properly

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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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')
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda