grayrouter.js 1.85 KB
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();
		}
	}
}