koa路由

2018-10-15  本文已影响13人  冷小谦

1.原生路由
网站页面由多个页面组成,通过ctx.request.path可以获取用户请求的路径。

const Koa = require("koa");
const app = new Koa();

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";
 }
};

app.use(main);
app.listen(2001);

2.koa-route模块
koa封装了一个koa-route模块,专门来处理路由。

const Koa = require("koa");
const app = new Koa();

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 koa";
 }

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

先定义变量 ctx.response.body模板写入,然后,app.use(route.get("路径",变量))

上一篇 下一篇

猜你喜欢

热点阅读