koa中的路由
2024-08-26 00:49:46
原生路由
网站一般都有多个页面。通过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
最新文章
- 基于AngularJS的企业软件前端架构[转载]
- JS 模板引擎 BaiduTemplate 和 ArtTemplate 对比及应用
- CSS3 功能
- Jquery的attr属性
- YUI Array 之dedupe(快速去重)
- iOS开发人员必看的精品资料(100个)
- TensorFlow构建卷积神经网络/模型保存与加载/正则化
- Flask学习 三 web表单
- [luogu3380][bzoj3196]【模板】二逼平衡树【树套树】
- Quick Search Articles in My Blog
- A1130. Infix Expression
- P5239 回忆京都
- day15--JavaScript
- [13]Windows 内核情景分析 --- 网络通信
- mysql修改lower_case_table_names产生的问题
- Space Shooter 学习
- 贪心算法:Codevs 1044 拦截导弹
- display:table和display:table-cell结合使用
- 15) maven dependency scope
- THINKPHP URL模块大小写导致404问题