Basic usage of koa-router
koa-router
is one of the core middleware components in the Koa2 ecosystem for handling routing. It offers a clean API design, making it easy to define routing rules, process request parameters, and support nested middleware. With it, developers can quickly build RESTful APIs or dynamic page routing.
Installation and Basic Configuration
First, install koa-router
via npm:
npm install koa-router
Import and initialize the router in a Koa2 application:
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
Defining Routing Rules
Basic GET/POST Routes
Define routes using router.get()
or router.post()
:
router.get('/', async (ctx) => {
ctx.body = 'Homepage content';
});
router.post('/api/login', async (ctx) => {
ctx.body = { success: true };
});
Dynamic Route Parameters
Use the :param
syntax to capture dynamic parameters:
router.get('/user/:id', async (ctx) => {
ctx.body = `User ID: ${ctx.params.id}`;
});
Support for regex constraints on parameter formats:
router.get('/article/:year(\\d{4})', async (ctx) => {
ctx.body = `Year: ${ctx.params.year}`;
});
Route Middleware
Single Route Middleware
Insert validation logic before route handling:
const auth = async (ctx, next) => {
if (!ctx.headers.token) ctx.throw(401);
await next();
};
router.get('/admin', auth, async (ctx) => {
ctx.body = 'Admin Panel';
});
Route Prefix Grouping
Create route groups using prefix
:
const apiRouter = new Router({ prefix: '/api' });
apiRouter.get('/users', async (ctx) => {
ctx.body = ['User1', 'User2'];
});
app.use(apiRouter.routes());
Request Handling Details
Retrieving Request Parameters
Handling URL query strings:
router.get('/search', async (ctx) => {
const { keyword = '' } = ctx.query;
ctx.body = `Search keyword: ${keyword}`;
});
Parsing POST request bodies requires koa-bodyparser
:
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
router.post('/submit', async (ctx) => {
const { name } = ctx.request.body;
ctx.body = `Received submission: ${name}`;
});
Setting Response Status Codes
Manually specifying HTTP status codes:
router.put('/resource/:id', async (ctx) => {
ctx.status = 204; // No Content
});
Advanced Routing Control
Chaining Multiple Middleware
Combining multiple middleware via arrays:
const log = async (ctx, next) => {
console.log(`Request path: ${ctx.path}`);
await next();
};
const check = async (ctx, next) => {
if (ctx.query.debug !== 'true') ctx.throw(403);
await next();
};
router.get('/debug', [log, check], async (ctx) => {
ctx.body = 'Debug info';
});
Redirect Handling
Implementing 301/302 redirects:
router.redirect('/old', '/new', 301);
Error Handling Solutions
Route-Level Error Catching
Handling specific errors within routes:
router.get('/protected', async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = { error: err.message };
}
});
405 Method Not Allowed
Automatically responding to unsupported HTTP methods:
app.use(router.routes()).use(router.allowedMethods());
When a PUT request is made to /api
, it will automatically return 405 Method Not Allowed
.
Practical Application Examples
RESTful API Implementation
Complete user resource interface example:
const usersRouter = new Router({ prefix: '/users' });
// Get user list
usersRouter.get('/', async (ctx) => {
ctx.body = await UserModel.findAll();
});
// Create new user
usersRouter.post('/', async (ctx) => {
const user = await UserModel.create(ctx.request.body);
ctx.status = 201;
ctx.body = user;
});
// User details
usersRouter.get('/:id', async (ctx) => {
const user = await UserModel.findById(ctx.params.id);
if (!user) ctx.throw(404);
ctx.body = user;
});
File Upload Route
Handling file uploads with koa-multer
:
const multer = require('@koa/multer');
const upload = multer({ dest: 'uploads/' });
router.post('/upload',
upload.single('avatar'),
async (ctx) => {
ctx.body = {
filename: ctx.file.originalname,
size: ctx.file.size
};
}
);
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:中间件安全注意事项