nodejs套接字挂起错误

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

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

  1. var proxy = httpProxy.createProxyServer();
  2. connect.createServer(
  3. connect.bodyParser(),
  4. require('connect-restreamer')(),
  5. function (req, res) {
  6. proxy.web(req, res, { target : 'XYZserver' });
  7. }
  8. ).listen(config.listenPort);

字符串
直到GET请求,一切都很好,但每当一个请求与一些机构,如POST,PATCH,PUT等请求,我得到错误:

  1. Error: socket hang up
  2. at createHangUpError (http.js:1472:15)
  3. at Socket.socketCloseListener (http.js:1522:23)
  4. at Socket.EventEmitter.emit (events.js:95:17)
  5. at TCP.close (net.js:466:12)


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

fd3cxomn

fd3cxomn1#

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

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

字符串
不是这个:

  1. app.use(someMiddleware);
  2. var httpProxy = require('http-proxy');
  3. var proxy = httpProxy.createProxyServer();
  4. app.use("/someroute", function(req, res) {
  5. proxy.web(req, res, { target: 'http://someurl.com'})
  6. });


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

展开查看全部
ffscu2ro

ffscu2ro2#

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

  1. // restream parsed body before proxying
  2. proxy.on('proxyReq', function(proxyReq, req, res, options) {
  3. if (req.body) {
  4. let bodyData = JSON.stringify(req.body);
  5. // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
  6. proxyReq.setHeader('Content-Type','application/json');
  7. proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
  8. // stream the content
  9. proxyReq.write(bodyData);
  10. }
  11. }

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

展开查看全部
9q78igpj

9q78igpj3#

需要捕捉代理的错误:

  1. var httpProxy = require('http-proxy');
  2. var proxy = httpProxy.createProxyServer({ target: argv.proxy_url })
  3. proxy.on('error', function(err, req, res) {
  4. res.end();
  5. })

字符串

sd2nnvve

sd2nnvve4#

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

  1. const webapitargetUrl = 'https://posttestserver.com/post.php';
  2. var bodyParser = require('body-parser');
  3. app.use(bodyParser.urlencoded({ extended: false }));
  4. app.use(bodyParser.json()); // support json encoded bodies
  5. var https = require('https');
  6. var stamproxy = httpProxy.createProxyServer({
  7. target: 'https://localhost:8888',
  8. changeOrigin: true,
  9. agent : https.globalAgent,
  10. toProxy : true,
  11. secure: false,
  12. headers: {
  13. 'Content-Type': 'application/json'
  14. }
  15. });
  16. stamproxy.on('proxyReq', function(proxyReq, req, res, options) {
  17. console.log("proxying for",req.url);
  18. if (req.body) {
  19. console.log("prxyReq req.body: ",req.body);
  20. // modify the request. Here i just by removed ip field from the request you can alter body as you want
  21. delete req.body.ip;
  22. let bodyData = JSON.stringify(req.body);
  23. // in case if content-type is application/x-www-form-urlencoded -> we need to change to application/json
  24. proxyReq.setHeader('Content-Type','application/json');
  25. proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
  26. // stream the content
  27. console.log("prxyReq bodyData: ",bodyData);
  28. proxyReq.write(bodyData);
  29. }
  30. console.log('proxy request forwarded succesfully');
  31. });
  32. stamproxy.on('proxyRes', function(proxyRes, req, res){
  33. proxyRes.on('data' , function(dataBuffer){
  34. var data = dataBuffer.toString('utf8');
  35. console.log("This is the data from target server : "+ data);
  36. });
  37. });
  38. app.use(compression());
  39. app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
  40. app.use(Express.static(path.join(__dirname, '..', 'static')));
  41. var sessions = require("client-sessions");
  42. app.use(sessions({
  43. secret: 'blargadeeblargblarg',
  44. cookieName: 'mysession'
  45. }));
  46. app.use('/server/setserverip', (req, res) => {
  47. console.log('------------ Server.js /server/setserverip ---------------------------------');
  48. req.mysession.serverip += 1;
  49. console.log('session data:');
  50. console.log(req.mysession.serverip)
  51. console.log('req.body:');
  52. console.log(req.body);
  53. // Proxy forwarding
  54. stamproxy.web(req, res, {target: webapitargetUrl});
  55. console.log('After calling proxy serverip');
  56. });

字符串

展开查看全部
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)包含在包中。这里是文档中的一个例子。

  1. const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');
  2. const proxy = createProxyMiddleware({
  3. /**
  4. * Fix bodyParser
  5. **/
  6. onProxyReq: fixRequestBody,
  7. });

字符串

mnemlml8

mnemlml88#

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

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

字符串

展开查看全部

相关问题