@RequestBody注解、
用户登录添加 购物车时候,发生点击添加购物车无效果问题;
用户登录,需对用户进行token 校验,添加购物车,用户购物车=查询本地购物车+用户账户中购物车;
在用户未登录状态时候是没有任何问题的,单单对本地购物车Local Storage进行操作/
该问题后端不会报错,前端也不会报错,毕竟网关过滤 添加正确、仅仅断点跟踪显示、一个疏忽,ε=(´ο`*)))唉
前端发送json数据 ,绑定到Cart 对象上, 使用 @RequestBody
@Autowired
private CartService cartService;
@PostMapping
public ResponseEntity<Void> addCart(@RequestBody Cart cart) {
Boolean flag=cartService.addCart(cart);
if (flag) {
return ResponseEntity.ok().build();
}
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
addCart() {
cart = {
skuId: this.sku.id,
title: this.sku.title,
image: this.images[0],
price: this.sku.price,
num: this.num,
ownSpec: this.sku.ownSpec
};
// 判断用户的登录状态
ly.http.get("/auth/verify").then(resp => {
// 已登录,redis 、发送到后台
ly.http.post("/cart",cart).then(resp=>{
// 跳转
window.location.href = "http://www.leyou.com/cart.html";
}).catch(resp=>{
console.log("登录失败");
});
}).catch(resp => {
// 没登录,localstorage
let carts = ly.store.get("carts");
if (carts) {
//判断此sku有没有加入过到购物车中
let storeCart = carts.find(ct => ct.skuId === cart.skuId);
if (storeCart) {//已经加入过
storeCart.num = storeCart.num + cart.num;
} else {//还未加入过
carts.push(cart);
}
} else {
//还是新的没有动过
carts = [];
carts.push(cart);
}
ly.store.set("carts", carts);
// 跳转
window.location.href = "http://www.leyou.com/cart.html";
});
}
@RequestBody接收的是一个Json对象的字符串,而不是一个Json对象。
然而在ajax请求往往传的都是Json对象,后来发现用 JSON.stringify(data)的方式就能将对象变成字符串。同时ajax请求的时候也要指定dataType: “json”,contentType:“application/json” 这样就可以轻易的将一个对象或者List传到Java端