socket与nodejs挂起错误

cod*_*ode 7 javascript sockets proxy node.js

我想为一些我不是管理员的XYZ服务器设置代理.然后我想对请求和响应头进行一些分析,然后对请求和响应主体进行分析.所以我使用的是http-proxy https://github.com/nodejitsu/node-http-proxy

这就是我在做的事情:

  var proxy = httpProxy.createProxyServer();


  connect.createServer(
    connect.bodyParser(),
    require('connect-restreamer')(),
    function (req, res) {
      proxy.web(req, res, { target : 'XYZserver' });
    }
  ).listen(config.listenPort);
Run Code Online (Sandbox Code Playgroud)

Upto GET请求一切都很好,但每当有一些请求,如POST,PATCH,PUT等请求时,我得到错误:

Error: socket hang up
    at createHangUpError (http.js:1472:15)
    at Socket.socketCloseListener (http.js:1522:23)
    at Socket.EventEmitter.emit (events.js:95:17)
    at TCP.close (net.js:466:12)
Run Code Online (Sandbox Code Playgroud)

我谷歌很多,但没有找到任何线索的错误.我使用'proxy.web'的'ws:true'选项启用套接字代理,但仍然是相同的错误.

Mic*_*ael 20

我有一个类似的问题,并通过将我的代理代码移到其他节点中间件之上来解决它.

这个:

var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
app.use("/someroute", function(req, res) {
    apiProxy.web(req, res, { target: 'http://someurl.com'})
});

app.use(someMiddleware);
Run Code Online (Sandbox Code Playgroud)

不是这个:

app.use(someMiddleware);

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
app.use("/someroute", function(req, res) {
    proxy.web(req, res, { target: 'http://someurl.com'})
});
Run Code Online (Sandbox Code Playgroud)

我的具体问题是将BodyParser中间件置于代理之上.我没有做太多的挖掘,但它必须以某种方式修改了请求,当请求最终到达它时,它破坏了代理库.


ric*_*din 12

只是为了完整起见,实在模块之间的集成问题body-parserhttp-proxy,在规定这个线程.

如果你不能改变中间件的顺序; 在代理请求之前,您可以重新调整已解析的正文.

// restream parsed body before proxying
proxy.on('proxyReq', function(proxyReq, req, res, options) {
    if (req.body) {
        let bodyData = JSON.stringify(req.body);
        // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
        proxyReq.setHeader('Content-Type','application/json');
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
        // stream the content
        proxyReq.write(bodyData);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这个f*****问题上已经失去了2天.希望能帮助到你!

  • 你是一个英雄。 (2认同)

Kro*_*oid 5

需要捕获代理的错误:

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({ target: argv.proxy_url })

proxy.on('error', function(err, req, res) {
    res.end();
})
Run Code Online (Sandbox Code Playgroud)


Vla*_*k Y 5

在浪费了一天多的时间并遵循了nodejitsu/node-http-proxy 问题中的一些帖子之后,我能够使其正常工作,这要归功于 riccardo.cardin。我决定发布完整的示例以节省您的时间。下面的示例使用 server expressbody-parser(req.body 中间件)和当然的http-proxy来代理和转发请求到 3rd 方服务器。

const webapitargetUrl = 'https://posttestserver.com/post.php'; 

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies

var https = require('https');
  var stamproxy = httpProxy.createProxyServer({
      target: 'https://localhost:8888',
      changeOrigin: true,
      agent  : https.globalAgent, 
      toProxy : true,
      secure: false,
      headers: {
      'Content-Type': 'application/json'
      } 
    });

  stamproxy.on('proxyReq', function(proxyReq, req, res, options) {
      console.log("proxying for",req.url);
      if (req.body) {
        console.log("prxyReq req.body: ",req.body);
        // modify the request. Here i just by removed ip field from the request you can alter body as you want
        delete req.body.ip;
        let bodyData = JSON.stringify(req.body);
        // in case if content-type is application/x-www-form-urlencoded -> we need to change to application/json
        proxyReq.setHeader('Content-Type','application/json');
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
        // stream the content
        console.log("prxyReq bodyData: ",bodyData);
        proxyReq.write(bodyData);
      }
      console.log('proxy request forwarded succesfully');
  });

  stamproxy.on('proxyRes', function(proxyRes, req, res){    
    proxyRes.on('data' , function(dataBuffer){
        var data = dataBuffer.toString('utf8');
        console.log("This is the data from target server : "+ data);
    }); 
  });


app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));

app.use(Express.static(path.join(__dirname, '..', 'static')));


var sessions = require("client-sessions");
app.use(sessions({
  secret: 'blargadeeblargblarg',
  cookieName: 'mysession'
}));

app.use('/server/setserverip', (req, res) => {

    console.log('------------ Server.js /server/setserverip  ---------------------------------');
    req.mysession.serverip += 1;

    console.log('session data:');
    console.log(req.mysession.serverip)
    console.log('req.body:');
    console.log(req.body);

    // Proxy forwarding   
    stamproxy.web(req, res, {target: webapitargetUrl});
    console.log('After calling proxy serverip');

});
Run Code Online (Sandbox Code Playgroud)