In Koa, data is returned to the frontend by setting the ctx.body property within your route handlers. This approach leverages Koa’s ability to automatically serialize objects into JSON responses when they are assigned to ctx.body. Here’s a step-by-step explanation:
-
Define Your Route Handler: Create an async function for your route, where you perform operations like fetching data from a database or API.
-
Set Response Data: Assign the desired data to ctx.body. Koa will automatically serialize this data into JSON format and set appropriate headers.
-
Handle Different Content Types: For non-JSON responses (like static files), use middleware such as koa–send or manually set ctx.type.
-
Custom Headers and Status Codes: Adjust the response status using ctx.status and add custom headers with ctx.set() if needed.
Example Code:
1 2 3 4 5 6 7 8 9 |
const Koa = require(‘koa’); const app = new Koa(); app.use(async (ctx) => { ctx.body = { message: ‘Hello from Koa!’ }; }); app.listen(3000); |
When accessed, this will send a JSON response with the specified data to the frontend.
Leave a Reply
You must be logged in to post a comment.