koa2学习2--koa-router

在前一篇中,我们对于所有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...');

转载于:https://my.oschina.net/qiongleee/blog/1860769

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值