乐闻世界logo
搜索文章和话题

Detailed explanation of Koa Context object ctx core properties and usage methods

2月21日 15:53

Koa's Context object (ctx) is a core concept that encapsulates Node.js's request and response objects into a single object, providing a more concise API through proxy pattern.

Core properties and methods of ctx object:

Request-related properties:

  • ctx.request: Koa's Request object
  • ctx.req: Node.js native request object
  • ctx.request.url: Request URL
  • ctx.request.method: Request method
  • ctx.request.header: Request header object
  • ctx.request.query: Parsed query string
  • ctx.request.querystring: Raw query string
  • ctx.request.path: Request path
  • ctx.request.body: Request body (requires body-parser middleware)

Response-related properties:

  • ctx.response: Koa's Response object
  • ctx.res: Node.js native response object
  • ctx.response.body: Response body
  • ctx.response.status: Response status code
  • ctx.response.header: Response header object
  • ctx.response.type: Response Content-Type
  • ctx.response.length: Response Content-Length

Convenient access (directly through ctx):

  • ctx.url: Equivalent to ctx.request.url
  • ctx.method: Equivalent to ctx.request.method
  • ctx.header: Equivalent to ctx.request.header
  • ctx.query: Equivalent to ctx.request.query
  • ctx.body: Equivalent to ctx.response.body
  • ctx.status: Equivalent to ctx.response.status
  • ctx.type: Equivalent to ctx.response.type

Other important properties:

  • ctx.state: Recommended namespace for passing information between middleware
  • ctx.app: Application instance reference
  • ctx.cookies: Cookie manipulation utility
  • ctx.throw(): Throw HTTP errors
  • ctx.assert(): Assertion check

Code example:

javascript
app.use(async (ctx) => { // Get request info const url = ctx.url; const method = ctx.method; const query = ctx.query; // Set response ctx.status = 200; ctx.type = 'application/json'; ctx.body = { message: 'Hello Koa' }; // Use state to pass data ctx.state.user = { id: 1, name: 'John' }; // Throw error if (!ctx.query.token) { ctx.throw(401, 'Token required'); } });

Design advantages of ctx object:

  1. Conciseness: Reduces code redundancy, improves development efficiency
  2. Consistency: Unified API interface, reduces learning cost
  3. Flexibility: Supports both convenient access and direct native object manipulation
  4. Extensibility: Can extend ctx object functionality through middleware
标签:Koa