有时候GET会返回304而不是200

时间:2017-06-27 20:23:03

标签: node.js

我正在使用node.js和mongodb来创建我的第一个电子商务网站。到目前为止,我已经非常善于解决所有问题。这是我留在后端的唯一问题。

问题:当我点击"添加到包"在我的网站上,它将产品大约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>

2 个答案:

答案 0 :(得分:1)

我无法确定您用于创建应用的堆栈。看起来你正在使用Express.js进行路由但是,我可以告诉你为什么你得到304.

来自维基百科:

  

304未修改(RFC 7232)
  表示自请求标头If-Modified-Since或If-None-Match指定的版本以来未对资源进行修改。在这种情况下,由于客户端仍然有先前下载的副本,因此无需重新传输资源。[24]

304意味着“嘿,还记得我发给你的最后一个答案吗?它没有改变”,因此你的浏览器会重播它从缓存中收到的最后一个响应,而不会发生任何数据传输。

这意味着您的已添加。但由于它是完全相同的数据包,而不是再给200一个完全相同的数据,服务器只发出304。

BTW :您的API不是很安静。我建议使用POST创建新记录,而不是将GET发送到其他网址。我建议阅读REST API设计。一旦掌握了它,它就非常简单。

答案 1 :(得分:0)

TL; DR:使用POST请求而不是GET请求。

GET请求应该用于获取内容。 GET请求不应影响应用程序的状态(即服务器的状态)。

在您的情况下,将商品添加到购物袋显然是修改服务器的状态

如果您不相信,check out this answer

  

GET在HTTP协议中以这种方式定义。它应该是幂等和安全的。

如果您使用POST请求,它不仅会解决您的问题,而且还会阻止其他一些可能的错误。 (而且它会更正确。)

相关问题