0

Every other time I load the page with an ajax call to most_voted I get the following error. Why is this happening?

Error

http.js:692
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.

Controller

// Add Voted Attribute
add_voted_attribute = function(user, product, callback) {
    Vote.find({ product: product._id, user: user._id }).exec(function(err, vote) {
        if (vote.length) {
            product       = product.toObject();
            product.voted = true;
            if (callback) { callback(product) };
        } else {
            product       = product.toObject();
            product.voted = false;
            if (callback) { callback(product) };
        };
    });
};


// Show Most Voted Products
exports.most_voted = function(req, res) {
        Product.find().sort({votes: -1}).limit(10).populate('user', 'name username').exec(function(err, products) {
            var products_with_voted_attribute = [];
            products.forEach(function(p){
                add_voted_attribute(req.user, p, function(product){
                    products_with_voted_attribute.push(product);
                    if (products_with_voted_attribute.length === 10) { 
                        eventEmitter.emit('mostVoted', products_with_voted_attribute); 
                    };
                });
            });
        });
        // Event Listener
        eventEmitter.on('mostVoted', function(products)  {
            products.sort(function(obj1, obj2) {
                return obj2.votes - obj1.votes;
            });
            res.jsonp(products);
        });
};
ac360
  • 7,735
  • 13
  • 52
  • 91
  • This is probably a duplicate of http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent – helderdarocha Feb 05 '14 at 01:46
  • 1
    Sounds like you're emitting multiple `mostVoted` events, but you can only send one response… – Bergi Feb 05 '14 at 01:51

2 Answers2

1

You can only call res.jsonp once per request. Calling this multiple times causes headers to be sent multiple times (Content-Type).

Charlie Key
  • 3,440
  • 1
  • 21
  • 12
0

The eventEmitter was firing multiple times. I'm not sure why this is, but I solved it by simply removing the event listener after it fires once. This fix required only one line of code:

// Event Listener
        eventEmitter.on('mostVoted', function(products)  {
            eventEmitter.removeAllListeners('mostVoted'); // Line of code to remove listener
ac360
  • 7,735
  • 13
  • 52
  • 91