接入已有Koa项目

若当前已有开发好的koa项目,也可以部分接入maty框架,不影响旧功能。

利用maty.js的mount功能,示例如下

const Koa = require('koa');
const Router = require('koa-router');
const maty = require('maty');

const app = new Koa();
const router = new Router();

// 挂载maty到某个 路径开头 下
const servePath = '/maty';
const serve = maty();
serve.mount(servePath, app); // ctx.path startsWith /maty

// 屏蔽原服务
app.use(async (ctx, next) => {
  if (ctx.path.startsWith(servePath)) {
    return;
  }

  await next();
});

// 原项目服务
router.get('/home', (ctx, next) => {
  ctx.body = 'original home page';
});

app
  .use(router.routes())
  .use(router.allowedMethods());

app.listen(8080);

这样,访问 http://localhost:8080/home 则是原有服务,而访问 http://localhost:8080/maty/serve 这样的/maty开头的路径则由maty提供服务。

Last updated