i can‘t use hprose with koa to share a RPC service
o70078 opened this issue · 2 comments
o70078 commented
when i use it with koa,the nodejs will throw this exception:
Uncaught Exception:
Error: Can't set headers after they are sent.
this is my code:
it‘s could run,but can't call RPC
var app = new Koa();
function hello(name) {
return "Hello " + name + "!";
}
const service = new hproseServer();
service.add(hello);
app.use(async (ctx: Router.IRouterContext, next: () => Promise<any>) => {
if (ctx.path === "/api/SystemInfomation") {
service.handle(ctx.req, ctx.res);
return;
}
await next();
});
app.listen(port);
andot commented
刚才更新了一下,这个问题修复了。但是要改一下代码,把下面这句:
service.handle(ctx.req, ctx.res);
改成
await service.handle(ctx.req, ctx.res);
就可以了,因为 service.handle 是异步的,不加 await,后面的代码就先执行了。所以,等 hprose 输出 header 的时候,koa 已经输出别的数据了。我改了之后,handle 方法的返回值变成了一个 Promise 对象,完成时,这个值会变成 true,所以 await 它就可以保证执行成功了。
另外,koa 好像不会自己加 200 状态码,我又加了输出 200 状态码的语句。不然默认会返回 404。
总之,这个问题已经改好了。非常感谢您的反馈~
o70078 commented
thank you very much