-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
91 lines (54 loc) · 1.87 KB
/
app.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const Koa = require('koa');
const render = require('./src/index');
const path = require('path');
const bodyParser=require('koa-bodyparser')
const controller = require('./controller');
//引入子模块子路由
const router = require('koa-router')();
const jstreeapi=require('./router/jstreeapi.js')
const user=require('./router/admin/user.js')
const app = new Koa();
app.use(function (ctx, next) { //设置上下文公共信息
ctx.state = ctx.state || {};
ctx.state.now = new Date();
ctx.state.ip = ctx.ip;
ctx.state.version = '2.0.0';
return next();
});
// 第一个middleware是记录URL以及页面执行时间:
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
var
start = new Date().getTime(),
execTime;
await next();
execTime = new Date().getTime() - start;
ctx.response.set('X-Response-Time', `${execTime}ms`);
});
// 第二个middleware处理静态文件:
let staticFiles = require('./static-files');
app.use(staticFiles('/static/', __dirname + '/static'));
app.use(staticFiles('/dist/', __dirname + '/dist'));
// 第三个middleware解析POST请求:
app.use(bodyParser());
// 第四个middleware负责给ctx加上render()来使用Nunjucks:
render(app, {
root: path.join(__dirname, 'view') , //挂在render 设置模板配置项
extname: '.html',
});
// 最后一个middleware处理URL路由:
app.use(controller());
router.use('/jstreeapi',jstreeapi)
router.use('/user',user)
app.use(router.routes()).use(router.allowedMethods())
// app.use(async function (ctx) {
// const users = [{ name: 'Dead Horse' }, { name: 'Jack' }, { name: 'Tom' }];
// await ctx.render('index', { // 渲染content模板
// users
// });
// });
app.listen(3000);
console.log('open http://localhost:3000');
app.on('error', function (err) {
console.log(err.stack);
});