Import Koa:
const Koa = require('koa');
const app = new Koa();
A comprehensive cheat sheet for Koa.js, covering essential concepts, middleware, routing, and common functionalities.
Import Koa:
|
Starting the server:
|
Basic middleware:
|
|
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 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 |
Using
|
Route parameters:
|
|
Handles GET requests. |
|
Handles POST requests. |
|
Handles PUT requests. |
|
Handles DELETE requests. |
|
Handles PATCH requests. |
Applying middleware to specific routes:
|
Parsing request body using
|
Ensure |
|
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. |
Setting cookies:
Getting cookies:
|
Signed cookies require setting a
|
Using
|
Emitting errors for centralized logging: |
|
|
Throws an error with the specified status and message. Example: |
|
Alternative way to set status and body for custom error pages. |
Example error-handling middleware:
|