原生路由

网站一般都有多个页面。通过ctx.request.path可以获取用户请求的路径,由此实现简单的路由。

const main = ctx => {
  if (ctx.request.path !== '/') {
    ctx.response.type = 'html';
    ctx.response.body = '<a href="/">Index Page</a>';
  } else {
    ctx.response.body = 'Hello World';
  }
};

koa-route 模块

原生路由用起来不太方便,我们可以使用封装好的koa-route模块。

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

const about = ctx => {
  ctx.response.type = 'html';
  ctx.response.body = '<a href="/">Index Page</a>';
};

const main = ctx => {
  ctx.response.body = 'Hello World';
};

app.use(route.get('/', main));
app.use(route.get('/about', about));

上面代码中,根路径/的处理函数是main/about路径的处理函数是about

访问 http://127.0.0.1:3000/about ,效果与上一个例子完全相同。

 

 

参考链接:http://www.ruanyifeng.com/blog/2017/08/koa.html

 

相关文章:

  • 2022-12-23
  • 2021-09-27
  • 2022-12-23
  • 2021-07-01
  • 2021-09-21
  • 2022-12-23
  • 2021-06-22
  • 2021-09-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2018-06-21
  • 2021-12-27
  • 2022-12-23
  • 2019-05-18
相关资源
相似解决方案