我正在使用 Waterline ORM 在 mongo DB 中插入新的用户数据。这是我的 Controller 操作的代码。
function *(){
var self = this;
var attributes= this.request.body
var userModel = this.models.user;
userModel.create(attributes).exec(function(err, model){
self.type = 'application/json';
self.body = {success:true,description:"user Created"};
});
}
当我尝试执行请求时,出现以下错误:
...../node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/connection/base.js:245
throw message;
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:331:11)
我不是 Koa 专家,但我认为这是因为这是一个异步过程,并且答案消息是之前写的。
谁能帮帮我吗?我非常有兴趣了解这项技术。
最佳答案
I think that it is because this is an async process and the answer message was written before.
是的。 Koa 不知道查询,因此它会在查询执行完成之前继续完成响应。
您可以向 Koa yield
一个函数
来包装查询并通知其完成。
function *() {
// ...
yield function (done) {
userModel.create(attributes).exec(function (err, model) {
self.type = 'application/json';
self.body = {success:true,description:"user Created"};
done(err);
});
}
}
此类 thunk 的使用在 documentation of co
中得到了进一步演示。 ,其中koa
is built on ,使用thunkify
生成这样的函数。
关于node.js - KOA响应错误水线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25351218/