How to send JSON response using Koa


json koa node Tutorials

Hello! If you are from Ukraine, Belarus, Poland or India and looking for a job in Software Development, please reach me out by email.

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