梗概

示例

const Koa = require('koa');
const app = new Koa();
 
app.use(async (ctx, next) => {
    try {
        // 检查是否需要终止请求-响应循环
        if (ctx.request.query.terminate === 'true') {
            ctx.body = '请求已终止';
            // 终止请求-响应循环
            return;
        }
 
        await next();
    } catch (error) {
        console.error(error);
        ctx.status = 500;
        ctx.body = '服务器错误';
    }
});
 
app.use(async (ctx) => {
    ctx.body = 'Hello, Koa!';
});
 
app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});

在上面的示例中,我们创建了一个Koa应用程序,并添加了两个中间件。第一个中间件检查查询参数是否为’true’,如果是,则返回’请求已终止’并终止请求-响应循环。这样可以避免后续中间件执行,直接返回响应给客户端。