How can I split my koa routes into separate files?

前端 未结 7 1168
一向
一向 2021-01-30 04:20

I\'m trying to figure out how to split my routes into separate files.

I have this so far, but it doesn\'t work. I just get Not found when I try to access

相关标签:
7条回答
  • 2021-01-30 05:13

    You can put all your routes inside a single folder called routes, then loop through all files in that folder, require them and init. That way for any new route, just create a file in routes folder and thats it.

    So something like this:

    index.js

    const Koa = require("koa");
    const logger = require("koa-logger");
    const bodyParser = require("koa-bodyparser");
    
    const app = new Koa();
    
    app.use(logger());
    app.use(bodyParser());
    
    require("./routes")(app);
    
    const server = app.listen(config.server.port);
    
    module.exports = server;
    

    /routes/index.js

    const fs = require("fs");
    const path = require("path");
    const baseName = path.basename(module.filename);
    
    const routes = fs
        .readdirSync(path.join(__dirname))
        .filter(
            file =>
                file.indexOf(".") !== 0 &&
                file !== baseName &&
                file.slice(-3) === ".js"
        )
        .map(file => require(path.join(__dirname, file)));
    
    module.exports = function(app) {
        for (var router of routes) {
            app.use(router.routes());
        }
    };
    

    Then inside /routes folder you would have like

    /routes/user.js

    /routes/customer.js

    which are all router exports such as

    /routes/auth.js

    const Router = require("koa-router");
    const authControllers = require("../controllers/auth");
    
    const {
        jwtAuth,
        login,
        register,
        forgotPassword,
        resetPassword,
        getAuthenticatedUser
    } = authControllers;
    
    const router = new Router({ prefix: "/auth" });
    
    router.post("/register", register);
    router.post("/login", login);
    router.post("/forgot-password", forgotPassword);
    router.post("/reset-password/:resetToken", resetPassword);
    router.get("/profile", jwtAuth, getAuthenticatedUser);
    
    module.exports = router;
    
    0 讨论(0)
提交回复
热议问题