grayroute.js
3.48 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/**
* 灰度界面代理中间件
* @author h1bomb
*/
var request = require('request');
var config = require('../config/gray');
/**
* 灰度界面配置
* @param {Object} proxyRoute
* @return {Function} 返中间件
*/
module.exports = function(proxyRoute) {
/**
* 灰度界面中间件
* @param {Object} req 请求对象
* @param {Object} res 响应对象
* @param {Function} next 执行下个中间件
* @return {void} 无返回
*/
return function(req, ress, next) {
//日志记录器
var logger = req.app.logger;
//方法名称
var method = req.method;
//访问路由路径
var path = req.route?req.route.path:'';
//路由的hash key
var key = proxyRoute.genKey(method,path);
//登出,清掉cookie
if(path === '/logout') {
req.session.gray = null;
next();
return;
}
//如果新系统路由没有,代理到老平台
if(!proxyRoute.interfacesConfig[key]) {
//老系统调用地址
var callUrl = config.url + req.originalUrl;
//gray 透传cookie
var options = {
method:method,
url:callUrl,
timeout:config.timeout,
headers: {
'Cookie':req.session.gray
}
}
if(!req.session.gray) {
logger.log('warn','grayroute: cookie missed',req.session.user);
}
//如果是Ajax请求加上 Ajax头
if(req.headers['x-requested-with']) {
options.headers['X-Requested-With'] = 'XMLHttpRequest';
}
if(req.headers['referer']) {
options.headers['Referer'] = req.headers['referer'];
}
//如果是POST,设置form表单的传参
if(method === "POST") {
options.form = req.body;
}
logger.log('info','grayroute: request options: %j',options,{});
//发起代理请求
request(options,callback);
//代理回调
function callback(err,res,body) {
if(err) {
logger.log('error','grayroute: request error:',err);
ress.status(500).send('');
} else if(res&&res.statusCode === 200) {
setGrayCookie(req,res);
var ContentType = res.caseless.get('Content-Type');
ress.append('Content-Type',ContentType);
ress.send(body);
} else if(res&&res.statusCode === 302) {
var curCookie = setGrayCookie(req,res);
if(!curCookie||curCookie.length<1) {
res.session.user = null;
}
//跳转
ress.redirect(res.caseless.get('location'));
} else if(res){
ress.status(res.statusCode).send(body);
} else {
ress.status(500).send('500 ERROR!');
}
}
} else {
//当不是老系统的URL,需要访问老系统保持session
request({
method:'GET',
url: config.url + config.sessionKeep,
headers: {
'Cookie':req.session.gray
}
},function(err,res,body){
var code = res?res.statusCode:'no response';
logger.log('info','grayroute: session keep status:'+code);
});
next();
}
}
}
/**
* 灰度cookie设置
* @param {Object} req express request
* @param {Object} res request的响应
*/
function setGrayCookie(req,res) {
//cookie透传到老系统
var cookie = res.caseless.get('set-cookie');
//如果没有设置到session
if(cookie && cookie.length>0 && !req.session.gray) {
req.session.gray = cookie[0];
}
return cookie;
}