原生路由

网站一般都有多个页面。通过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

最新文章

  1. 基于AngularJS的企业软件前端架构[转载]
  2. JS 模板引擎 BaiduTemplate 和 ArtTemplate 对比及应用
  3. CSS3 功能
  4. Jquery的attr属性
  5. YUI Array 之dedupe(快速去重)
  6. iOS开发人员必看的精品资料(100个)
  7. TensorFlow构建卷积神经网络/模型保存与加载/正则化
  8. Flask学习 三 web表单
  9. [luogu3380][bzoj3196]【模板】二逼平衡树【树套树】
  10. Quick Search Articles in My Blog
  11. A1130. Infix Expression
  12. P5239 回忆京都
  13. day15--JavaScript
  14. [13]Windows 内核情景分析 --- 网络通信
  15. mysql修改lower_case_table_names产生的问题
  16. Space Shooter 学习
  17. 贪心算法:Codevs 1044 拦截导弹
  18. display:table和display:table-cell结合使用
  19. 15) maven dependency scope
  20. THINKPHP URL模块大小写导致404问题

热门文章

  1. DRF--介绍和安装
  2. docker 部署 HFish(集群部署)
  3. Azure EA (3) 使用Postman访问海外Azure Billing API
  4. Zookeeper 到底能帮我们解决哪些问题?
  5. Maven配置教程详解
  6. PC端页面适应不同的分辨率的方法
  7. IOS之UIColor
  8. Arduino控制舵机
  9. https抓包 Fiddler
  10. 1.监控软件zabbix-入门