Catalog / Koa.js Cheatsheet
Koa.js Cheatsheet
A comprehensive cheat sheet for Koa.js, covering essential concepts, middleware, routing, and common functionalities.
Koa.js Fundamentals
Basic Setup
Import Koa:
|
Starting the server:
|
Basic middleware:
|
Context Object
|
Koa Request object (similar to Node’s |
|
Koa Response object (similar to Node’s |
|
Shorthand for setting response body ( |
|
Shorthand for setting response status ( |
|
Object containing route parameters. |
Middleware
Middleware is a function that will be invoked on every request.
|
Middleware execution order is determined by the order in which they are added to the app. |
Use |
Routing in Koa
Basic Routing
Using
|
Route parameters:
|
HTTP Methods
|
Handles GET requests. |
|
Handles POST requests. |
|
Handles PUT requests. |
|
Handles DELETE requests. |
|
Handles PATCH requests. |
Route Middleware
Applying middleware to specific routes:
|
Working with Request & Response
Request Body
Parsing request body using
|
Ensure |
Response Headers
|
Sets a response header field. |
|
Gets a request header field. |
|
Sets the Content-Type response header. |
|
Sets the Content-Disposition to ‘attachment’ to signal the client to download the file. |
Cookies
Setting cookies:
Getting cookies:
|
Signed cookies require setting a
|
Error Handling
Basic Error Handling
Using
|
Emitting errors for centralized logging: |
|
Custom Error Pages
|
Throws an error with the specified status and message. Example: |
|
Alternative way to set status and body for custom error pages. |
Error Middleware
Example error-handling middleware:
|