我试图了解以下代码的工作原理以及后面的代码是什么。
var Todo = require('./models/database');
function getTodos(res){
Todo.find()
.sort('-created_at')
.exec(function(err, todos) {
if (err) return console.error(err);
// ISSUE HERE
res.json(todos, function(err){
if (err) console.log(err);
}); // return all todos in JSON format
});
};
module.exports = function(app) {
// api ---------------------------------------------------------------------
// get all todos
app.get('/api/todos', function(req, res) {
getTodos(res);
});
// update a todo
app.get('/api/todos/:todo_id/:replacedText', function(req, res) {
console.dir(req.params.todo_id);
console.dir(req.params.replacedText);
Todo.update({ _id : req.params.todo_id},
{$set: {text: req.params.replacedText}},
function(err, todo) {
if (err) res.send(err);
getTodos(res);
});
});
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
以上代码有效。但当我把Todo.find()下的代码作为:
// ISSUE HERE
res.json(todos); // return all todos in JSON format
这没有用。我收到以下错误:
http http.js:689
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
at ServerResponse.header (\node_modules\express\lib\response.js:595:10)
at ServerResponse.send (\node_modules\express\lib\response.js:143:12)
at ServerResponse.json (\node_modules\express\lib\response.js:229:15)
at Promise.<anonymous> (\app\routes.js:70:12)
at Promise.<anonymous> (\node_modules\mongoose\node_modules\mpromise\lib\promise.js:177:8)
at Promise.emit (events.js:95:17)
at Promise.emit (\node_modules\mongoose\node_modules\mpromise\lib\promise.js:84:38)
at Promise.fulfill (\node_modules\mongoose\node_modules\mpromise\lib\promise.js:97:20)
at Promise.resolve (\node_modules\mongoose\lib\promise.js:114:23)
帮助我弄清楚,这里发生了什么。