在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:steambap/koa-tree-router开源软件地址:https://github.com/steambap/koa-tree-router开源编程语言:JavaScript 100.0%开源软件介绍:Koa tree routerKoa tree router is a high performance router for Koa. Features
How does it work?The router relies on a tree structure which makes heavy use of common prefixes, it is basically a compact prefix tree (or just Radix tree). This module's tree implementation is based on julienschmidt/httprouter. Installation# npm
npm i koa-tree-router
# yarn
yarn add koa-tree-router Usageconst Koa = require("koa");
const Router = require("koa-tree-router");
const app = new Koa();
const router = new Router();
router.get("/", function(ctx) {
ctx.body = "hello, world";
});
app.use(router.routes());
app.listen(8080); APIRouter([options])Instance a new router. const router = require('koa-tree-router')({
onMethodNotAllowed(ctx){
ctx.body = "not allowed"
}
}) on(method, path, middleware)Register a new route. router.on('GET', '/example', (ctx) => {
// your code
}) Shorthand methodsIf you want to get expressive, here is what you can do: router.get(path, middleware)
router.delete(path, middleware)
router.head(path, middleware)
router.patch(path, middleware)
router.post(path, middleware)
router.put(path, middleware)
router.options(path, middleware)
router.trace(path, middleware)
router.connect(path, middleware) If you need a route that supports all methods you can use the router.all(path, middleware) use(middleware)You can add middleware that is added to all future routes: router.use(authMiddleware);
router.get("/foo", (ctx) => { /* your code */ });
router.get("/bar", (ctx) => { /* your code */ });
router.get("/baz", (ctx) => { /* your code */ }); This is equivalent to: router.get("/foo", authMiddleware, (ctx) => { /* your code */ });
router.get("/bar", authMiddleware, (ctx) => { /* your code */ });
router.get("/baz", authMiddleware, (ctx) => { /* your code */ }); Caveat: routesReturns router middleware. app.use(router.routes()); nested routesA way to create groups of routes without incuring any per-request overhead. const Koa = require("koa");
const Router = require("koa-tree-router");
const app = new Koa();
const router = new Router();
const group = router.newGroup("/foo");
// add a handler for /foo/bar
group.get("/bar", function(ctx) {
ctx.body = "hello, world";
});
app.use(router.routes());
app.listen(8080); Middleware added with ctx.paramsThis object contains key-value pairs of named route parameters. router.get("/user/:name", function() {
// your code
});
// GET /user/1
ctx.params.name
// => "1" How to write routesThere are 3 types of routes: 1.Static
2.Named Named parameters have the form
3.Catch-all Catch-all parameters have the form
Typescript SupportThis package has its own declaration files in NPM package, you don't have to do anything extra. License |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论