每次其他时,我都会通过对most_voted
的ajax调用加载页面,但是出现以下错误。为什么会这样?
错误
http.js:692
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
控制器
// 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);
});
};
答案 0 :(得分:1)
每个请求只能调用一次res.jsonp。多次调用会导致多次发送标题(内容类型)。
答案 1 :(得分:0)
eventEmitter多次触发。我不确定为什么会这样,但我通过在触发一次之后删除事件监听器来解决它。此修复只需要一行代码:
// Event Listener
eventEmitter.on('mostVoted', function(products) {
eventEmitter.removeAllListeners('mostVoted'); // Line of code to remove listener