从零一起学koa2(3)---koa-router中间件

版权声明:转载请注明博客地址谢谢。 https://blog.csdn.net/buppt/article/details/79252618

简介

先安装koa-router中间件。

npm install --save koa-router

新建文件app.js ,代码如下。

const Koa = require('koa');
const Router = require('koa-router');
 
const app = new Koa();
const router = new Router();
 
router.get('/', function (ctx, next) {
    ctx.body="Hello Koa";
})
router.get('/todo',(ctx,next)=>{
    ctx.body="Todo page"
});
 
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000,()=>{
  console.log('starting at port 3000');
});

执行node app.js,打开http://localhost:3000/ 可以看到Hello Koa,打开http://localhost:3000/todo 可以看到Todo page ,使用其他路由地址会出现Not Found 。
这样我们就使用中间件简单实现了路由。
这里用到了get请求,get请求会在下一篇细讲,allowedMethods()就是保证接受的是GET请求,当客户端发送POST请求时,就会直接返回失败。

多层路由

新建app.js文件,代码如下:

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

//子路由1
let home = new Router();
home.get('/home', async(ctx)=>{
    ctx.body="Hello /home/home/";
});
home.get('/todo',async(ctx)=>{
    ctx.body="Hello /home/todo/";
});
//子路由2 
let page = new Router();
page.get('/home', async(ctx)=>{
    ctx.body="Hello /page/home/";
});
page.get('/todo',async(ctx)=>{
    ctx.body="Hello /page/todo/";
});
//父级路由
let router = new Router();
router.use('/home',home.routes(),home.allowedMethods());
router.use('/page',page.routes(),page.allowedMethods());

app.use(router.routes()).use(router.allowedMethods());
app.listen(3000,()=>{
  console.log('starting at port 3000');
});

通过上面代码的方法,先设置子类路由,再设置父类路由。
执行node app.js 打开http://localhost:3000/page/todo会显示 Hello /page/todo/ 。打开http://localhost:3000/home/todo会显示 Hello /home/todo/

这样就可以根据自己的需求,设计不同层次的路由了。

猜你喜欢

转载自blog.csdn.net/buppt/article/details/79252618