首页 > 解决方案 > 尝试从客户端发送数据但 req.session 无法正常工作

问题描述

我正在尝试发布请求,当我使用邮递员时它非常成功,但我试图从我的客户端发送它。我想发布购物车,但结果我不断发布数量为 1 的项目,无论我发布该请求多少次。解决此问题并以正常方式发布请求的最佳解决方案是什么?

这是我的发帖请求:

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);
  }
});

这是Cart代码:

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;
    }
  }
}

这是我放在按钮上的功能@click.prevent="addToCart()"

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

我从前端的 axios 服务发送这个:

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

当我尝试在客户端与之交互时,没有警告或错误。这是我在后端得到的输出(不断重复单个产品的信息,但这在客户端正常工作):

在此处输入图像描述

标签: javascriptexpressclient

解决方案


如果您使用的是 angular、vue、react 或任何支持路由的前端框架。您无需使用res.redirect更改路线和获取数据。

您如何使用res.send(cart)返回购物车数据并在前端进行重新路由。

async postCart(productId){
    cartService.post(`/add-to-cart/${productId}`);
    // history.push('/your-next-route')
}

推荐阅读