曲线球路由器
此软件包是一个简单的路由器 曲线球。 。 。 .
安装
npm install @curveball/router
开始
最简单和推荐的形式如下:
import { Application } from '@curveball/kernel';
import router from '@curveball/router';
const app = Application();
app.use(
router('/foo/:id', ctx => {
// the 'id' is available via ctx.params.id
})
);
也可以采用以下语法进行每方法的路由.
import { Application } from '@curveball/kernel';
import router from '@curveball/router';
const app = Application();
app.use(
router('/foo/:id')
.get( ctx => { /* GET requests */ })
.post( ctx => { /* POST requests */ })
);
您可以指定 1 个或多个中间件 。 以下示例运行 两个虚构的中间软件在一个路线.
const app = Application();
const route = router(
'/foo/:id',
myAuthMiddleware,
myBodyparser,
ctx => {
ctx.response.body = 'success!';
}
);
app.use(route);
访问其他中间软件中匹配的路由
匹配的路由被添加到 Curveball 上下文中, 供其他中间软件访问 如果需要的话(如访问请求记录)。 可在 路由器已执行 .
import { Application, Context } from '@curveball/kernel';
import router from '@curveball/router';
const app = Application();
app.use(async (ctx: Context, next) => {
await next();
// Will be '/foo/:id'
const matchedRoute = ctx.router?.matchedRoute;
});
app.use(
router('/foo/:id', ctx => {
ctx.response.body = '/foo/' + ctx.state.params.id;
});
);