app.js
2.81 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* yoho-activity-platform app
* @author: leo<qi.li@yoho.cn>
* @date: 2017/6/23
*/
'use strict';
const cors = require('cors');
const path = require('path');
const express = require('express');
const config = require('./config/common');
const bluebird = require('bluebird');
const ynLib = require('yoho-node-lib');
const {SqlHelper, Yoho} = require('./utils');
const bodyParser = require('body-parser');
const compression = require('compression');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const favicon = require('serve-favicon');
const moment = require('moment');
const _ = require('lodash');
const pkg = require('./package.json');
let logger;
const app = express();
app.locals.devEnv = app.get('env') === 'development';
app.locals.isProduction = app.get('env') === 'production';
app.locals.version = pkg.version;
app.locals.startTime = moment().format('YYYYMMDDHH');
// 全局注册library
ynLib.global(config);
logger = global.yoho.logger;
global.Promise = bluebird;
global.yoho.utils = {
mysqlCli: new SqlHelper(config.mysql.database),
yoho: Yoho
};
app.use(cookieSession({
name: 'yoho_activity',
secret: 'activity@yoho',
maxAge: 24 * 60 * 60 * 1000
}));
app.use(compression());
app.use(favicon(path.join(__dirname, '/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public/dist')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use((req, res, next) => {
req.user = {}; // 全局的用户数据
req.yoho = {}; // req和res绑定yoho对象,用于传递全局数据
req.cookies.from = 'action';
next();
});
app.use(global.yoho.httpCtx());
app.enable('trust proxy');
app.use(global.yoho.hbs({
extname: '.hbs',
defaultLayout: 'layout',
layoutsDir: path.join(__dirname, 'doraemon/views'),
partialsDir: path.join(__dirname, 'doraemon/views/partial'),
views: path.join(__dirname, 'doraemon/views'),
helpers: _.assign(global.yoho.helpers, require('./utils/helpers'))
}));
try {
// 允许跨域
app.use(cors({
credentials: true,
origin: config.corsAllowOrigin
}));
const errorHandler = require('./doraemon/middleware/error-handler');
const devtools = require('./doraemon/middleware/devtools');
if (app.locals.devEnv) {
app.use(devtools());
}
// docker验证项目是否正常发布
app.use('/node/status.html', (req, res) => {
return res.status(200).end();
});
require('./dispatch')(app);
app.all('*', errorHandler.notFound); // 404
// YOHO 后置中间件
app.use(errorHandler.serverError);
} catch (err) {
logger.error(err);
}
app.listen(config.port, function() {
logger.info(`yoho-activity-platform started successfully, listening on port:${config.port}`);
});