在Express.js中自定义callback得到

我有一个在我的app.js

app.get('/api/personnel', api.personnel); 

调用这个函数作为callback从mongo加载一些数据:

 exports.personnel = function(req, res) { var docs; db.personnel.find(function(err, docs) { if (err) { logError(err); } else { res.json({ personnel: docs }); } }); }; 

这工作得很好,但我真的希望能够调用callback函数完成时的testing目的:

 exports.personnel = function(req, res, callback) { var docs; db.personnel.find(function(err, docs) { if (err) { logError(err); } else { res.json({ personnel: docs }); } callback(); }); 

当从应用程序调用函数时, callback()是空的,并给我一个错误:

 Error: Can't set headers after they are sent. 

我如何去打电话给我的callback?

你可以包装这个函数来插入附加的函数参数:

 exports.personnel = function(req, res, callback) { var docs; db.personnel.find(function(err, docs) { if (err) { logError(err); } else { res.json({ personnel: docs }); } }); /////////////////////////////////////////////////// var callback = ...; pp.get('/api/personnel', function(req, res) { api.personnel(req, res, callback); }); 

Express中的第三个元素总是保留给next()callback(如在中间件中所见)。 如果你想要“回拨”,但不想搞砸快,让我们来破解!

 exports.personnel = function(req, res, callback) { var docs; db.personnel.find(function(err, docs) { if (err) { logError(err); } else { res.json({ personnel: docs }); } if(process.env.NODE_ENV === 'test') callback(); }); 

那么,当你想testing的时候,在你的shell中export NODE_ENV=test