koa中的路由

做~自己de王妃 提交于 2019-12-05 17:19:21

原生路由

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!