const Koa = require('koa');
const router = require('koa-router')();
const nunjucks = require('nunjucks');
const app = new Koa();
// 配置 Nunjucks
nunjucks.configure(__dirname + '/views', {
autoescape: true, // 是否自動轉義輸出
noCache: true // 是否禁用模板快取,方便開發除錯
});
// 將 Nunjucks 新增為 Koa 中介軟體
app.use(async (ctx, next) => {
ctx.render = nunjucks.render;
await next();
});
// 配置 router
router.get('/', async (ctx, next) => {
ctx.body = await ctx.render('index.html', { title: 'Index page', content: 'Hello Index!' });
});
router.get('/post/:id.html', async (ctx, next) => {
ctx.body = await ctx.render('post.html', { title: 'Post page', content: 'Hello Post!' });
});
// 將 router 新增為 Koa 中介軟體
app.use(router.routes());
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});