UNPKG

1.57 kBJavaScriptView Raw
1
2var http = require('http');
3var debug = require('debug')('dev-server:proxy');
4
5
6
7module.exports = function(app) {
8 app.proxy = function(url, config) {
9 app.use(url, function(req, res, next) {
10 var httpPath = (config.path || '') + req.path;
11 var headers = {};
12
13 Object.keys(req.headers).forEach(function(name) {
14 if (name !== 'host' && name !== 'connection')
15 headers[name] = req.headers[name];
16 });
17
18 headers.host = config.hostname || config.host;
19
20 var client = http.request({
21 host: config.host,
22 hostname: config.hostname,
23 port: config.port,
24 localAddress: config.localAddress,
25 socketPath: config.socketPath || config.socket,
26 method: req.method,
27 path: httpPath
28 }, function(proxyres) {
29 debug('server connection - response');
30
31 res.statusCode = proxyres.statusCode;
32 if (proxyres.headers['content-type'])
33 res.setHeader('content-type', proxyres.headers['content-type']);
34
35 proxyres.on('data', function(data) {
36 res.write(data);
37 });
38
39 proxyres.on('end', function() {
40 debug('res end');
41 res.end();
42 });
43
44 proxyres.on('error', function() {
45 debug('PROXY ERROR');
46 res.statusCode = 500;
47 res.end();
48 });
49
50 });
51
52 req.setEncoding('utf8');
53
54 req.on('data', function(data) {
55 client.write(data);
56 });
57
58 req.on('end', function(data) {
59 debug('req end');
60 client.end();
61 });
62
63 });
64 };
65};