-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
52 lines (44 loc) · 1.17 KB
/
server.ts
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
import Koa from 'koa';
import Router from 'koa-router';
import koaBody from 'koa-body';
import serve from 'koa-static';
import mount from 'koa-mount';
import logger from 'koa-logger';
import render from 'koa-art-template';
import routers from './routers';
const app = new Koa();
// error handing
app.use( async (ctx: any, next) => {
try{
await next();
if(ctx.status === 404) {
ctx.throw(404)
}
} catch(e) {
let { status, message, stack } = e;
if(!status) {
status = 500;
}
console.log(status, message, stack);
await ctx.render('error', { status, message, stack });
}
});
// art-template
render(app, {
root: __dirname + '/views',
extname: '.html',
debug: process.env.NODE_ENV !== 'production'
});
// static
app.use(mount("/static", serve(__dirname + '/static')));
// logger
app.use(logger());
// body
app.use(koaBody());
// routers
const router = Router();
routers.forEach(r => router[r.method](r.path, r.action));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
console.log('koa server started, please type localhost:3000 in browser address');