路由管理

原生路由

通过请求路径 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(3000);

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));

koa-router

使用 koa-generator 生成的项目自带路由管理模块

app.js

// 引入路由文件
const index = require('./routes/index')
const users = require('./routes/users')
// 加载路由
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

routes/index

const router = require('koa-router')()
// 访问 http://localhost:3000/ 即可输出 Hello Koa 2! 渲染模板 index.pug
router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})
// 访问 http://localhost:3000/string 直接输出字符串
router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})
// 访问 http://localhost:3000/string 直接输出json
router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})
module.exports = router

routes/users

const router = require('koa-router')()
// 添加路由前缀
router.prefix('/users')
// 访问 http://localhost:3000/users 直接输出字符串
router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})
// 访问 http://localhost:3000/users/bar 直接输出字符串
router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})
module.exports = router

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress