示例
const Koa = require('koa');
const app = new Koa();
// 发送字符串响应
app.use(async ctx => {
ctx.body = 'Hello, World!';
});
// 发送JSON响应
app.use(async ctx => {
ctx.body = { message: 'Hello, World!' };
});
// 发送HTML响应
app.use(async ctx => {
ctx.type = 'text/html';
ctx.body = '<h1>Hello, World!</h1>';
});
// 发送文件响应
app.use(async ctx => {
await send(ctx, 'path/to/file.html');
});
app.listen(3000);
console.log('Server running on http://localhost:3000');在上面的示例中,我们展示了如何使用Koa发送不同类型的响应。可以通过设置ctx.body来发送字符串、JSON和HTML响应,也可以通过send方法发送文件响应。