Koa入门2 koa-router 封装 组合 中间件

接着 Koa入门继续 传送门— Koa入门

我们监听的是3000端口 但是路径没有限制,所以输入以下路径都是OK的
http://localhost:3000/****
在这里插入图片描述
这样的话怎么处理 ?
按理说 我们想要每个路由对应不同的页面渲染
实现如下

// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa');

// 创建一个Koa对象表示web app本身:
const app = new Koa();

app.use(async (ctx, next) => {
   
  const url = ctx.url;
  ctx.response.type = 'text/html';
  switch (url){
   
    case '/':
      ctx.response.body = '<h1>Hello, koa2!</h1>';
      break;
    case '/haha':
      ctx.response.body = '<h1>haha!</h1>';
      break;
    case '/xixi':
      ctx.response.body = '<h1>xixi!</h1>';
      break;
  }
  await next(); // 调用下一个middleware
});

// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');

在这里插入图片描述
这样处理感觉会很笨重 所以我们还是需要做下集中处理的 当当当 koa-router 出现了
首先 安装依赖

npm install koa-router

package.json

{
   
  "scripts": {
   
    "start": "node app.js"
  },
  "dependencies": {
   
    "koa": "^2.12.1",
    "koa-router": "^9.0.1"
  }
}
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa');

// 创建一个Koa对象表示web app本身:
const app = new Koa();
// 注意require('koa-router')返回的是函数:

const route = require('koa-router');
const router = route()

app.use(async (ctx, next) => {
   
  console.log(`Process ${
     ctx.request.method} ${
     ctx.request.url}...`);
  await next();
});

// add url-route:
router.get('/', async (ctx, next) => {
   
  ctx.response.body = '<h1>Index</h1>';
});
router.get('/:name', async (ctx, next) => {
   
  var name = ctx.params.name;
  ctx.response
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值