-
Notifications
You must be signed in to change notification settings - Fork 234
Expand file tree
/
Copy pathsendProxyRequest.js
More file actions
92 lines (80 loc) · 2.65 KB
/
sendProxyRequest.js
File metadata and controls
92 lines (80 loc) · 2.65 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
'use strict';
var chunkLength = require('../../lib/chunkLength');
function sendProxyRequest(Container) {
var req = Container.user.req;
var res = Container.user.res;
var bodyContent = Container.proxy.bodyContent;
var reqOpt = Container.proxy.reqBuilder;
var options = Container.options;
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
var corporateProxyServer = process.env.http_proxy || process.env.HTTP_PROXY ||
process.env.https_proxy || process.env.HTTPS_PROXY;
var noProxyVal = process.env.no_proxy;
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
var noProxy = [];
if (noProxyVal) {
noProxy = noProxyVal.split(',');
}
function isHostOutside() {
return !noProxy.includes(reqOpt.host);
}
if (corporateProxyServer && isHostOutside()) {
var HttpsProxyAgent = require('https-proxy-agent');
reqOpt.agent = new HttpsProxyAgent(corporateProxyServer);
}
return new Promise(function(resolve, reject) {
var protocol = Container.proxy.requestModule;
var proxyReq = protocol.request(reqOpt, function(rsp) {
var chunks = [];
rsp.on('data', function(chunk) { chunks.push(chunk); });
rsp.on('end', function() {
Container.proxy.res = rsp;
Container.proxy.resData = Buffer.concat(chunks, chunkLength(chunks));
resolve(Container);
});
rsp.on('error', reject);
});
proxyReq.on('socket', function(socket) {
if (options.timeout) {
socket.setTimeout(options.timeout, function() {
proxyReq.abort();
});
}
});
// TODO: do reject here and handle this later on
proxyReq.on('error', function(err) {
// reject(error);
if (err.code === 'ECONNRESET') {
res.setHeader('X-Timout-Reason',
'express-http-proxy timed out your request after ' +
options.timeout + 'ms.');
res.writeHead(504, {'Content-Type': 'text/plain'});
res.end();
} else {
reject(err);
}
});
// this guy should go elsewhere, down the chain
if (options.parseReqBody) {
// We are parsing the body ourselves so we need to write the body content
// and then manually end the request.
//if (bodyContent instanceof Object) {
//throw new Error
//debugger;
//bodyContent = JSON.stringify(bodyContent);
//}
if (bodyContent.length) {
proxyReq.write(bodyContent);
}
proxyReq.end();
} else {
// Pipe will call end when it has completely read from the request.
req.pipe(proxyReq);
}
req.on('aborted', function() {
// reject?
proxyReq.abort();
});
});
}
module.exports = sendProxyRequest;