Koa Context 对象 ctx 的核心属性和使用方法详解
Koa 的 Context 对象(ctx)是将 Node.js 的 request 和 response 对象封装到一个对象中的核心概念,通过代理模式提供了更简洁的 API。ctx 对象的核心属性和方法:请求相关属性:ctx.request:Koa 的 Request 对象ctx.req:Node.js 原生的 request 对象ctx.request.url:请求 URLctx.request.method:请求方法ctx.request.header:请求头对象ctx.request.query:解析后的查询字符串ctx.request.querystring:原始查询字符串ctx.request.path:请求路径ctx.request.body:请求体(需要 body-parser 中间件)响应相关属性:ctx.response:Koa 的 Response 对象ctx.res:Node.js 原生的 response 对象ctx.response.body:响应体ctx.response.status:响应状态码ctx.response.header:响应头对象ctx.response.type:响应 Content-Typectx.response.length:响应 Content-Length便捷访问(直接通过 ctx):ctx.url:等同于 ctx.request.urlctx.method:等同于 ctx.request.methodctx.header:等同于 ctx.request.headerctx.query:等同于 ctx.request.queryctx.body:等同于 ctx.response.bodyctx.status:等同于 ctx.response.statusctx.type:等同于 ctx.response.type其他重要属性:ctx.state:推荐的命名空间,用于传递中间件之间的信息ctx.app:应用实例引用ctx.cookies:Cookie 操作工具ctx.throw():抛出 HTTP 错误ctx.assert():断言检查代码示例:app.use(async (ctx) => { // 获取请求信息 const url = ctx.url; const method = ctx.method; const query = ctx.query; // 设置响应 ctx.status = 200; ctx.type = 'application/json'; ctx.body = { message: 'Hello Koa' }; // 使用 state 传递数据 ctx.state.user = { id: 1, name: 'John' }; // 抛出错误 if (!ctx.query.token) { ctx.throw(401, 'Token required'); }});ctx 对象的设计优势:简洁性:减少了代码冗余,提高开发效率一致性:统一的 API 接口,降低学习成本灵活性:既支持便捷访问,也支持直接操作原生对象扩展性:可以通过中间件扩展 ctx 对象的功能