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