跳到主要内容

koa-router

2024年10月17日
柏拉文
越努力,越幸运

一、认识


koa-router 是一个为 Koa 提供的路由中间件,用于定义和管理 HTTP 路由。它允许你将不同的请求 URL 映射到特定的处理函数,从而使你的应用结构更清晰、可维护性更高。

二、API


三、语法


const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

// 定义路由
router.get('/', async (ctx) => {
ctx.body = 'Hello, Koa!';
});

router.get('/users/:id', async (ctx) => {
const id = ctx.params.id;
ctx.body = `User ID: ${id}`;
});

router.post('/users', async (ctx) => {
// 处理创建用户逻辑
ctx.body = 'User created!';
});

// 使用路由中间件
app.use(router.routes()).use(router.allowedMethods());

// 启动服务器
app.listen(3000, () => {
console.log('Server listening on port 3000');
});