1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| const Koa = require('koa') const co = require('co') const nunjucksViews = require('koa-nunjucks-promise') const router = require('koa-router') const mount = require('koa-mount') const server = require('koa-static') const session = require("koa-session2") const log4js = require('koa-log4')
require('./log') const logger = log4js.getLogger('app') logger.info('--------step into koa-------------')
const store = require('./store') const app = new Koa() const route = new router() app.use(nunjucksViews(`${__dirname}/views`, { ext: 'html', noCache: true, watch: true, filters: { json: function(str) { return JSON.stringify(str, null, 2) } }, globals: { } })) app.use(mount('/static', server(`${__dirname}/public`)))
app.use(log4js.koaLogger(log4js.getLogger('http'), { level: 'auto' }))
app.use(session({ key: "sessionId", store: new store(), maxAge: 5000 })) route.get('/', co.wrap(function* (ctx) { logger.debug(' this is test log')
if(ctx.session.view === undefined) { ctx.session.view = 0 } else { ctx.session.view += 1 } console.log('viewNum', ctx.session.view) yield ctx.render('index', {title: 'Nunjucks', content: 'Feifeiyu yeah!'}) })) route.get('/route/test', co.wrap(function* (ctx) { logger.info(' this is test log2') ctx.body = 'feifeiyu nuaa' })) app.use(route.routes()) .use(route.allowedMethods()) app.listen(3000, () => console.log('server started, port 3000')) module.exports = app
|