当前位置: 首页 > 工具软件 > koa-log4js > 使用案例 >

koa-router的使用

岑驰
2023-12-01
const Koa = require("koa");
const Router = require("koa-router");
const app = new Koa();
const router = new Router();
const userRouter = new Router({ prefix: "/user" });

//多重中间件用法
const auth = async(ctx, next) => {
    if (ctx.url !== "/user") {
        ctx.throw(401);
    }
    await next();
}

router.get("/", auth, (ctx) => {
    ctx.body = "这是主页";
})
userRouter.get("/", auth, (ctx) => {
    ctx.body = "这是用户列表";
})
userRouter.get("/:id", auth, (ctx) => {
    ctx.body = "这是用户:" + ctx.params.id;
})
app.use(router.routes())
app.use(userRouter.routes())
app.listen(3000, function() {
    console.log("请访问127.0.0.1:3000");
})
 类似资料: