I created an app in nodejs and koa2
app.js
'use strict';
const Koa = require('koa');
const app = new Koa();
const port = 3000;
const router = require('./router');
const path = require("path")
const views = require("koa-views");
const bodyParser = require("koa-bodyparser");
const koastatic = require("koa-static");
app.use(koastatic(path.join( __dirname, "./static")))
app.use(views(path.join(__dirname, "./view"), {extension: "ejs"}))
router(app);
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
There are some router files in folder router, e.g.
index.js
'use strict';
const fs = require('fs');
module.exports = (app) => {
fs.readdirSync(__dirname).forEach(file => {
if (file === 'index.js') { return; }
const route = require(`./${file}`);
app.use(route.routes()).use(route.allowedMethods());
});
}
There are some pages that require login to access, e.g.
dashboard.js
'use strict';
const Router = require("koa-router");
const router = new Router({prefix: '/dashboard'});
router
.get('/', async (ctx, next) => {
let login = ctx.cookies.get('login') || "";
if (!login) {
ctx.redirect('/login');
} else {
let isexist = //check login status
if (isexist && login) {
await ctx.render("dashboard", {
current_service: "dashboard"
});
} else {
ctx.redirect('/login');
}
}
})
module.exports = router;
It works well, but there are lots of pages, if I use this way to determine these pages that require a login to access, it seems unreasonable, is there a better solution? Thank you.