grayrouter.js
1.85 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
var request = require("request");
var _ = require('lodash');
var md5=require("md5");
var fs=require("fs");
function addFiles(req) {
var body = {};
_.forEach(req.files, function (v, k) {
body[k] = fs.createReadStream(v.path);
});
_.merge(body, req.body);
return body;
}
module.exports=function(controllers){
var Iaccount=global.Register.system;
return function(err,req,res,next){
console.log(err);
console.log("req.originalUrl:"+req.originalUrl)
if(err.status=="404"){
var method = req.method.toLowerCase();
var path = req.route?req.route.path:'';
var callUrl = Iaccount.url + req.originalUrl;
//老系统调用地址
var options = {
method:method,
url:callUrl,
timeout:Iaccount.timeout,
headers: req.headers,
// useQuerystring:true,
form:req.body
}
//删除提交内容长度,代理会改变长度
delete options.headers['content-length'];
delete options.headers["accept-encoding"];
//设置代理host
options.headers['host'] = Iaccount.url.replace('http://','');
// console.log(options);
if(!req.session.gray) {
console.log('warn','grayroute: cookie missed');
} else {
options.headers['cookie'] = req.session.gray;
}
if(req.files && _.keys(req.files).length>0) {
options.formData = addFiles(req);
delete options.form;
}
console.log('info','grayroute: request options: %j',options,{});
console.log("代理:",options);
//发起代理请求
request(options).pipe(res);
}else{
request({
method:'GET',
url: Iaccount.url + Iaccount.sessionKeep,
headers: {
'Cookie':req.session.gray
}
},function(err,res,body){
var code = res?res.statusCode:'no response';
console.log('info','grayroute: session keep status:'+code);
});
next();
}
}
}