在前一篇中,我们对于所有http请求都返回相同的html。
1.没有路由管理
接下来,我们针对不同的URL调用不同的处理函数,并返回不同的结果。
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
if (ctx.request.path === '/') {
ctx.response.body = 'index page';
} else {
await next();
}
});
app.use(async (ctx, next) => {
if (ctx.request.path === '/test') {
ctx.response.body = 'TEST page';
} else {
await next();
}
});
app.use(async (ctx, next) => {
if (ctx.request.path === '/error') {
ctx.response.body = 'ERROR page';
} else {
await next();
}
});
app.listen(3000);
console.log('app start at port 3000 ...');
这样写虽然可以运行,但路由没有集中处理,维护麻烦。
我们需要一个集中处理URL的middleware,它根据不同的URL调用不同的处理函数,这样,我们才能专心为每个URL编写处理函数。koa-router应运而生。
2.安装koa-router
npm install koa-router --save
3.实现简单路由管理
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
// 打印请求URL
app.use(async (ctx, next) => {
console.log(`处理 ${ctx.request.method} ${ctx.request.url} ...`);
await next();
});
// 增加路由
// 使用router.get('/path', async fn)来注册一个GET请求
router.get('/', async (ctx, next) => {
ctx.response.body = '<h1>首页</h1>';
});
router.get('/hello/:name', async (ctx, next) => {
let name = ctx.params.name;
ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});
// 增加路由中间件
app.use(router.routes());
app.listen(3000);
console.log('app srarted at port 3000 ...');
4.实现多层路由管理
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
// 前台页面的路由
let front = new Router();
front.get('/', async (ctx, next) => {
ctx.response.body = "Hello /front";
});
front.get('/todo', async (ctx, next) => {
ctx.body = 'Hello /front/todo/';
});
// 后台页面的路由
let admin = new Router();
admin.get('/', async (ctx, next) => {
ctx.body = 'Hello /admin/';
});
admin.get('/todo', async (ctx, next) => {
ctx.body = 'Hello /admin/todo';
});
// 父级路由
let router = new Router();
router.use('/front', front.routes(), front.allowedMethods());
router.use('/admin', admin.routes(), admin.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
console.log('app started at port 3000...');