-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
89 lines (75 loc) · 1.85 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
const koa = require("koa");
const app = (module.exports = new koa());
const logger = require("./libs/logger");
const config = require("./config");
require("./libs/catch");
process.on("uncaughtException", err => {
console.log("uncaught error happen:");
console.dir(err.stack);
try {
var killTimer = setTimeout(function() {
process.exit(1);
}, 30000);
killTimer.unref();
} catch (e) {
logger.error("error when exit: %j", e.stack);
}
});
app.on("error", function(err, ctx) {
logger.error("server error, %j", err, err);
});
// cors
const cors = require("koa-cors");
app.use(
cors({
credentials: true
})
);
// request id
const instanceMark = Math.random()
.toString(36)
.substr(2, 6);
var globalReqId = 0;
app.use(async (ctx, next) => {
this.reqId = [instanceMark, globalReqId++].join(".");
await next();
});
// body parser
const bodyParser = require("koa-bodyparser");
app.use(bodyParser());
// helmet
const helmet = require("koa-helmet");
app.use(
helmet({
frameguard: false
})
);
// 上面frameguard:false 关不掉有问题
app.use(async (ctx, next) => {
await next();
// 默认X-Frame-Options: SAMEORIGIN会导致浏览器iframe标签抛错
// https://www.ietf.org/rfc/rfc7034.txt
ctx.response.remove("x-frame-options");
});
const visitlog = require("./middlewares/visitlog");
app.use(visitlog);
// 响应数据格式统一处理
const response = require("./middlewares/response");
app.use(response);
// 使用session
const session = require("koa-session");
app.use(session(config.session, app));
// 用户认证
// 路由
const routers = require("./middlewares/routes")("controllers");
routers.forEach(router => {
app.use(router.routes());
});
// 压缩
const compress = require("koa-compress");
app.use(compress());
if (!module.parent) {
let port = process.env.PORT || 3000;
app.listen(port);
logger.info("listening on port " + port);
}