node.js - KOA响应错误水线

标签 node.js sails.js waterline koa

我正在使用 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/

相关文章:

javascript - 在 CLI 中和通过 node.js 脚本运行时,执行 PHP 脚本有不同的结果

javascript - 如何处理从nodejs服务器下载图像?

sails.js - 从 javascript 对象构造水线模型对象

node.js - sails.js 蓝图按关系查询

javascript - 如何模拟 Later.JS 的时间

javascript - Webpack html 插件不生成 html

node.js - Bower to Sails - 我错过了什么?

javascript - 水线,在数组中查找数组

javascript - 填充条件失败

mongodb - Sailsjs 查找未设置字段的位置