javascript - 尝试从客户端发送数据但 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}`);
}
当我尝试在客户端与之交互时,没有警告或错误。这是我在后端得到的输出(不断重复单个产品的信息,但这在客户端正常工作):
解决方案
如果您使用的是 angular、vue、react 或任何支持路由的前端框架。您无需使用res.redirect
更改路线和获取数据。
您如何使用res.send(cart)
返回购物车数据并在前端进行重新路由。
async postCart(productId){
cartService.post(`/add-to-cart/${productId}`);
// history.push('/your-next-route')
}
推荐阅读
- jsp - 在 JSP 中获取地图的特定键的值
- amazon-web-services - Ansible CloudFormation 模块看不到 S3 对象
- javascript - 通过特定查询或突变重置缓存
- python-3.x - PyPlot 的奇怪网格行为
- python - 识别和计算数据框中前 x 个对象的统计信息
- python - 从元组列表中获取匹配项的值
- javascript - 在 Chart.js 中实现范围滑块
- powershell - 根据文件名时间戳powershell将文件移动到年/月文件夹中
- github - GitHub Pages URL 将“/”转换为“-”
- javascript - 使用移动应用程序发送和接收射频信号