Koa.js
Koa is a minimalist and expressive web framework for Node.js, designed to build web applications and APIs with a strong emphasis on async/await for handling requests and responses.
Core Concepts
-
Lightweight and Modular:
Koa provides a minimal core without built-in middleware, encouraging developers to add only what they need. -
Async/Await Middleware:
Middleware is written using async functions, making asynchronous code clean and readable. -
Context Object (
ctx
):
Thectx
object represents the request and response, providing methods and properties for interacting with them.
Basic Setup
-
Installation:
npm install koa
-
Simple Koa Server:
const Koa = require("koa");
const app = new Koa();
app.use(async (ctx) => {
ctx.body = "Hello, Koa!";
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Routing Example (Using koa-router
)
-
Install
koa-router
:npm install koa-router
-
Basic Routing:
const Koa = require("koa");
const Router = require("koa-router");
const app = new Koa();
const router = new Router();
router.get("/", (ctx) => {
ctx.body = "Welcome to Koa!";
});
router.get("/user/:id", (ctx) => {
ctx.body = `User ID: ${ctx.params.id}`;
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
Middleware Examples
-
Logging Middleware:
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
}); -
Error Handling Middleware:
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = { error: err.message };
ctx.app.emit("error", err, ctx);
}
}); -
Body Parsing Middleware (Using
koa-bodyparser
):npm install koa-bodyparser
const bodyParser = require("koa-bodyparser");
app.use(bodyParser());
app.use(async (ctx) => {
if (ctx.method === "POST") {
ctx.body = `Received: ${JSON.stringify(ctx.request.body)}`;
}
});
Common ctx
Methods
Method | Description |
---|---|
ctx.body | Sets the response body |
ctx.status | Sets the HTTP status code |
ctx.method | Access the request method |
ctx.url | Access the request URL |
ctx.request | Access request object |
ctx.response | Access response object |
ctx.params | Access route parameters (via router) |
ctx.query | Access query string parameters |
-
Use Koa Middleware:
Add essential middleware likekoa-router
,koa-bodyparser
, andkoa-static
to handle routing, parsing, and serving static files. -
Embrace Async/Await:
Koa’s async/await pattern makes it easy to handle asynchronous operations cleanly. -
Error Handling:
Implement global error-handling middleware early to catch and manage errors gracefully. -
Check Koa Documentation:
Visit the Koa Docs for deeper insights into the framework and advanced usage.