Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modified response body #860

Open
gangstaJS opened this issue Aug 6, 2015 · 4 comments
Open

Modified response body #860

gangstaJS opened this issue Aug 6, 2015 · 4 comments

Comments

@gangstaJS
Copy link

var httpProxy = require('http-proxy');
var cookie = require('cookie');
var _ = require('underscore');
var connect = require('connect');
var serveStatic = require('serve-static');
var colors = require('colors');
var fs = require('fs');



var proxy = httpProxy.createProxyServer({protocolRewrite: 'https'}),

    target = "https://example.com",

    staticDir = '.',

    port = 3000,

    filename = './app.html',

    newLength = 0,

    dataRead,

    match = null,

    app = connect();

// --


app
.use(serveStatic(staticDir))
.use(function(request, response) {
    match = /((?:\/j_).+)/i.exec(request.url);

    if(!match) {

      request.url = request.url+'?type=json'

      response.oldWrite = response.write;

      fs.readFile(filename, "utf8", function (err, d) {
        if(err) throw err;
        dataRead = d;       
      });

      response.write = function(data) {
        response.oldWrite(dataRead);
      }

      console.log('Proxy PAGE:'.gray + request.url);

    } else {
      console.log('Proxy JSON API:'.green + request.url.yellow);
    }



    if(request.headers.cookie) {
      var cookies = cookie.parse(request.headers.cookie);
    }      

    request.headers.host = 'mail.ex.ua';
    proxy.web(request, response, { target: target });  

});

// --

// --

proxy.on('proxyRes', function (proxyRes, req, res) {
  if(proxyRes.headers['set-cookie'] && proxyRes.headers['set-cookie'].length) {

    proxyRes.headers['set-cookie'] = _.map(proxyRes.headers['set-cookie'], function(el,n) {
      var token_obj = cookie.parse(el);
      return token_obj.token ? 'token=' + token_obj.token : el;
    });
  }

  if(!match) {
    proxyRes.headers['content-type'] = "text/html; charset=utf-8";
    // proxyRes.headers['content-length'] =10000;

    var headLen = proxyRes.headers['content-length'];




    var body = '';
    proxyRes.on('data', function(chunk) {
      body += chunk;
    });

    proxyRes.on('end', function() {
      dataRead = dataRead.toString().replace('_JSON_', body.toString());
      dataRead = new Buffer(dataRead, "binary");
      proxyRes.headers['content-length'] = dataRead.length;
    });

  }

});

// --

app.listen(port);
console.log(("Server is listening at port: "+port).bgGreen.white.bold);

Problem on this part code

var body = '';
    proxyRes.on('data', function(chunk) {
      body += chunk;
    });

    proxyRes.on('end', function() {
      dataRead = dataRead.toString().replace('_JSON_', body.toString());
      dataRead = new Buffer(dataRead, "binary");
      proxyRes.headers['content-length'] = dataRead.length;
    });

When END event is triggered it's too late to change content-length.

@shivambarsaley
Copy link

Any updates on this..
I am facing similar issue's

@gangstaJS
Copy link
Author

I am solved this removed content-length header

@Maxximl
Copy link

Maxximl commented Sep 21, 2021

Use this:
proxy.web(request, response, { target: target, selfHandleResponse: true });

@cawoodm
Copy link

cawoodm commented Jul 3, 2022

apiProxy.on('proxyRes', (proxyRes, req, res) => {
  var _write = res.write;
  var body = '';
  proxyRes.on('data', function(data) {
    data = data.toString('utf-8');
    body += data;
  });
  res.write = function(data) {
    try {
      // Modify Body Here
      body = body + '<hr>&copy; 2022 Me';
      // Don't forget to update Content-Length header
      proxyRes.headers['content-length'] = body.length;
      _write.call(res, body);
    } catch (e) {
      console.trace(e);
      console.error(e.message);
      throw e;
    }
  };
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants