我正在使用node.js和mongodb创建我的第一个电子商务网站。到目前为止,我对所有事情都非常满意。这是我在后端留下的唯一问题。有时GET返回304而不是200
问题:当我在我的网站上点击“Add to Bag”时,它会将产品添加到我的购物袋中约95%的时间,并在我的终端中返回“GET 200”。另外5%的时间没有将产品添加到我的购物袋中,并在我的终端中返回“GET 304”。
显示我的终端响应适当添加至购物袋,然后失败添加至购物袋
totalQty: 14,
totalPrice: 5250,
add: [Function],
updateQty: [Function],
reduceByOne: [Function],
removeItem: [Function],
generateArray: [Function] }
GET /add-to-bag/595258fadabeaab2357e0f1a 302 167.002 ms - 154
GET /products/595258ccdabeaab2357e0f18 200 210.705 ms - 4970
Bag {
items: { '595258fadabeaab2357e0f1a': { item: [Object], qty: 15, price: 5625 } },
totalQty: 15,
totalPrice: 5625,
add: [Function],
updateQty: [Function],
reduceByOne: [Function],
removeItem: [Function],
generateArray: [Function] }
GET /add-to-bag/595258fadabeaab2357e0f1a 302 157.734 ms - 154
GET /products/595258ccdabeaab2357e0f18 304 197.984 ms - -
购物袋型号
//gets the old bag
module.exports = function Bag(oldBag) {
this.items = oldBag.items || {};
this.totalQty = oldBag.totalQty || 0;
this.totalPrice = oldBag.totalPrice || 0;
//adds new item to bag
this.add = function(item, id) {
//checks if item already exists in bag
var storedItem = this.items[id];
if (!storedItem) {
storedItem = this.items[id] = {item: item, qty: 0, price: 0 };
}
//increase quantity and adjusts price
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
//updates total quantity and total price
this.totalQty++;
this.totalPrice+= storedItem.item.price;
};
this.generateArray = function() {
var arr = [];
for (var id in this.items) {
arr.push(this.items[id]);
}
return arr;
};
};
购物袋路线
router.get('/add-to-bag/:id', function(req, res, next) {
var productId = req.params.id;
var bag = new Bag(req.session.bag ? req.session.bag : {items: {}});
Product.findById(productId, function(err, product) {
if (err) {
return res.redirect('/');
}
bag.add(product, product.id);
req.session.bag = bag;
console.log(req.session.bag);
res.redirect('back');
});
});
我加入袋子视图
<!DOCTYPE html>
<div class="container">
<div class="row">
{{# each products}}
<div class="col-md-4">
<a href="/product/{{this._id}}">
<div class="thumbnail">
<img src="{{this.image}}">
<div class="caption">
<h3>{{this.name}}</h3>
<p>{{this.category.name}}</p>
<p>{{this.price}}</p>
<p><a href="/add-to-bag/{{this._id}}" class="btn btn-primary" align="center" role="button">Drop in Bag</a> </p>
</div>
</div>
</a>
</div>
{{/ each}}
</div>
</div>
不应该...那不是一个GET请求,而是POST或PUT?你正在执行一个动作,而不是获得信息 –