koa中的路由
原生路由
网站一般都有多个页面。通过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
个性签名:时间会解决一切