nodejs套接字挂起错误

z8dt9xmd  于 2023-11-17  发布在  Node.js
关注(0)|答案(8)|浏览(138)

我想为一些我不是管理员的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);

字符串
直到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)


我谷歌了很多,但没有发现任何线索是什么错了。我启用套接字代理与'ws:true'选项的'proxy.web',但仍然是同样的错误。

fd3cxomn

fd3cxomn1#

我也遇到过类似的问题,通过将代理代码移到其他节点中间件上解决了这个问题。
例如:

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);

字符串
不是这个:

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'})
});


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

ffscu2ro

ffscu2ro2#

为了完整起见,模块body-parserhttp-proxy之间确实存在集成问题,如this线程中所述。
如果你不能改变中间件的顺序,你可以在拒绝请求之前restream解析的主体。

// 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);
    }
}

字符串
我在这个问题上花了2天时间。希望它能帮上忙!

9q78igpj

9q78igpj3#

需要捕捉代理的错误:

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

proxy.on('error', function(err, req, res) {
    res.end();
})

字符串

sd2nnvve

sd2nnvve4#

在浪费了一天多的时间,并遵循了nodejitsu/node-http-proxy issues中的一些帖子之后,我能够让它工作,这要感谢riccardo.cardin。我决定发布完整的示例来保存你的时间。下面的示例使用服务器expressbody-parser(请求。主体中间件),当然还有http-proxy来代理和转发请求到第三方服务器。

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');

});

字符串

yi0zb3m4

yi0zb3m45#

http-proxy似乎与body-parser中间件不兼容。您可能希望将http-proxy中间件移到body-parser之前或停止使用body-parser
标签:Socket hangup while posting request to Node-http-proxy Node.js

sg2wtvxw

sg2wtvxw6#

我在 postputdelete 时遇到了这个问题,但在从chimurai / http-proxy-middleware读取this issue后,我已经做到了。

1-添加onProxyReq:https://github.com/chimurai/http-proxy-middleware/issues/40#issuecomment-249430255
2-需要注意的是,在请求头中需要添加Content-Type:application/json
**3-**没有body解析器的更改顺序

nwsw7zdq

nwsw7zdq7#

http-proxy-middleware是一个使用http-proxy的类似软件包,它是专门为以下目标创建的:
轻松配置代理中间件,用于连接、快速、浏览器同步等。
这个包继承了body解析器的相同问题,但是,修复(fixRequestBody)包含在包中。这里是文档中的一个例子。

const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');

const proxy = createProxyMiddleware({
  /**
    * Fix bodyParser
  **/
 onProxyReq: fixRequestBody,
});

字符串

mnemlml8

mnemlml88#

对于Post请求,此错误可能是由bodyParser消耗的stream引起的。您需要重新创建流并将其传递给代理。

app.use(bodyParser.json({
  // verify function has access to buff that contains the stream
  // create a new readable stream and save it to streamBody
  verify: (req, res, buf, encoding) => {
  const readableStream = Readable.from(buf);
  req.streamBody = readableStream
 }
}));
 // Your stream was already consumed by bodyParser you must pass it 
 // again to the param "buffer"
proxy.web(req, res, {
 target: "target-here",
 buffer: req.streamBody
});

字符串

相关问题