0
exports.deleteItem = function (req, res)
{
    var query = req.params.id;
    var cart = req.session.items;
    var index;

    _.each(cart,function (ticket)
    {
        if(ticket.id === query)
        {
           index = cart.indexOf(ticket);
            cart.splice(index,1);
        }
        return res.redirect(303, '/cart');
    });
};

I am using this function in my routes to perform a delete operation. It works for the first few items on my list, then suddenly stops and gives me the error "Can't set headers after they are sent."

$(document).ready(function() {
    $('.delete-from-cart').click(function(event)
    {
        $target = $(event.target);
        $.ajax({
            type: 'DELETE',
            url: '/cart/remove/' + $target.attr('data-item-id'),
            data: {
                _csrf: $target.attr('data-csrf')
            },
            success: function(response)
            {
                $target.parent().parent().remove();
                Materialize.toast('Ticket Removed', 4000);
                window.location.href = '/cart';
            },
            error: function(error)
            {
                Materialize.toast('Error', 4000);
                console.log(error);
            }
        });
    });
});
lagfvu
  • 597
  • 6
  • 21

1 Answers1

0

A single request was made, which means a single response should occur.

When you execute the _.each function I'm guessing that it works if there is one item but fails when there are multiple? This is because you are trying to send multiple responses when only one is permitted.

A good explanation for this can be found here: Error: Can't set headers after they are sent to the client

Community
  • 1
  • 1
Dennis
  • 3,962
  • 7
  • 26
  • 44