forked from zhaojun1998/Valine-Admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
77 lines (65 loc) · 1.97 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
'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 todos = require('./routes/todos');
var cloud = require('./cloud');
var app = express();
// 设置 view 引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static('public'));
// 加载云代码方法
app.use(cloud);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// 未处理异常捕获 middleware
app.use(function(req, res, next) {
var 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.get('/', function(req, res) {
res.render('index', { currentTime: new Date() });
});
// 可以将一类的路由单独保存在一个文件中
app.use('/todos', todos);
// 如果任何路由都没匹配到,则认为 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
res.status(err.status || 500);
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;