-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
89 lines (77 loc) · 2.19 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
'use strict';
var domain = require('domain');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cookieSession = require('cookie-session');
var qrcode = require('./routes/qrcode');
var cloud = require('./cloud');
var app = express();
// 加载云代码
app.use(cloud);
// 设置 view 引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// 设置cookie
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}));
// 未处理异常捕获 middleware
app.use(function(req, res, next) {
var d = null;
if (process.domain) {
d = process.domain;
} else {
d = domain.create();
}
d.add(req);
d.add(res);
d.on('error', function(err) {
console.error('uncaughtException url=%s, msg=%s', req.url, err.stack || err.message || err);
if(!res.finished) {
res.statusCode = 500;
res.setHeader('content-type', 'application/json; charset=UTF-8');
res.end('uncaughtException');
}
});
d.run(next);
});
// 可以将一类的路由单独保存在一个文件中
app.use('/qrcode', qrcode);
// 如果任何路由都没匹配到,则认为 404
// 生成一个异常让后面的 err handler 捕获
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// 如果是开发环境,则将异常堆栈输出到页面,方便开发调试
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) { // jshint ignore:line
var statusCode = err.status || 500;
if(statusCode === 500) {
console.error(err.stack || err);
}
res.status(statusCode);
res.render('error', {
message: err.message || err,
error: err
});
});
}
// 如果是非开发环境,则页面只输出简单的错误信息
app.use(function(err, req, res, next) { // jshint ignore:line
res.status(err.status || 500);
res.render('error', {
message: err.message || err,
error: {}
});
});
module.exports = app;