How to send JSON response using Koa


json koa node Tutorials

In Koa.js you don’t need to use some specific methods to make a JSON response.

For example, if you send a string:

app.use((ctx) => ctx.body = 'string');

the browser will show Content-Type equal to text/plain:

If you send an object or an array the browser will show Content-Type equal to application/json.

Examples:

app.use((ctx) => ctx.body = [1,2,3]);

app.use((ctx) => ctx.body = { a: 1, b: 2, c: [3, 4] });

Koa.js automatically converts ctx.body to JSON if it’s an object or an array.

comments powered by Disqus