'KoaJS: Ending a response
I have a simple koa
echo server:
var koa = require('koa');
var app = koa();
app.use(require('koa-trie-router')(app));
app.route('/echo/:word')
.post(function* (next) {
this.response.body = { echo: this.params.word };
yield next;
});
app.listen(3000);
When I curl that end point I see this:
* Connection #0 to host localhost left intact
{"echo":"hello"}%
But I can't figure out how to close that connection via the koa
api. How do I complete a response?
Solution 1:[1]
koa uses a middleware pattern. yield next
is used to go to the next middleware for your request handler. Since you don't have anymore middleware, you shouldn't yield next
in this case. Just set the body and let the function close.
Solution 2:[2]
Just use:
app.route('/echo/:word')
.post(function* (next) {
ctx.throw(401, { echo: this.params.word })
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mikefrey |
Solution 2 | Wilbert |