Can not set Header in KOA When using callback

青春壹個敷衍的年華 提交于 2019-12-01 06:01:15

问题


Recently I worked on a new project that used javascript callbacks. And I was using koa framework. But when I called this route :

function * getCubes(next) {
  var that = this;
     _OLAPSchemaProvider.LoadCubesJSon(function(result) {
    that.body = JSON.stringify(result.toString());
     });
}

I get this error :

_http_outgoing.js:331
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_outgoing.js:331:11)
at Object.module.exports.set (G:\NAP\node_modules\koa\lib\response.js:396:16)
at Object.length (G:\NAP\node_modules\koa\lib\response.js:178:10)
at Object.body (G:\NAP\node_modules\koa\lib\response.js:149:19)
at Object.body (G:\NAP\node_modules\koa\node_modules\delegates\index.js:91:31)
at G:\NAP\Server\OlapServer\index.js:42:19
at G:\NAP\Server\OlapServer\OLAPSchemaProvider.js:1599:9
at _LoadCubes.xmlaRequest.success (G:\NAP\Server\OlapServer\OLAPSchemaProvider.js:1107:13)
at Object.Xmla._requestSuccess (G:\NAP\node_modules\xmla4js\src\Xmla.js:2110:50)
at Object.ajaxOptions.complete (G:\NAP\node_modules\xmla4js\src\Xmla.js:2021:34)

回答1:


The problem is that your async call LoadCubesJSon() takes a while to return but Koa isn't aware of that and continues with the control flow. That's basically what yield is for.

"Yieldable" objects include promises, generators and thunks (among others).

I personally prefer to manually create a promise with the 'Q' library. But you can use any other promise library or node-thunkify to create a thunk.

Here is short but working example with Q:

var koa = require('koa');
var q = require('q');
var app = koa();

app.use(function *() {
    // We manually create a promise first.
    var deferred = q.defer();

    // setTimeout simulates an async call.
    // Inside the traditional callback we would then resolve the promise with the callback return value.
    setTimeout(function () {
        deferred.resolve('Hello World');
    }, 1000);

    // Meanwhile, we return the promise to yield for.
    this.body = yield deferred.promise;
});

app.listen(3000);

So your code would look as follows:

function * getCubes(next) {
    var deferred = q.defer();

    _OLAPSchemaProvider.LoadCubesJSon(function (result) {
        var output = JSON.stringify(result.toString());
        deferred.resolve(output);
    });

    this.body = yield deferred.promise;
}


来源:https://stackoverflow.com/questions/22037287/can-not-set-header-in-koa-when-using-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!