Socket hangup while posting request to Node-http-proxy Node.js

跟風遠走 提交于 2019-12-18 03:09:32

问题


I'm working in Node.js Project and I want node to act as a proxy for solr

For proxy: I used Node-http-proxy. the problem is that proxy work excellent in case of get requests but in case of post requests it results in socket hang up exception

Here is a sample of my node code

var express = require('express');
var router = express.Router();

var http = require('http');
var httpProxy = require('http-proxy')

var proxyOptions = {
  host: "127.0.0.1",
  port: 8983
};
var proxy = httpProxy.createProxyServer(proxyOptions);

// It works excellent in GET request
router.get('/solr/*', function(req, res) {
  proxy.web(req, res, {
    target: 'http://' + proxyOptions.host + ':' + proxyOptions.port
  });
})

// the socket hang up in post request
router.post('/solr/*', function(req, res) {
  console.log('Post Request');
  proxy.web(req, res, {
    target: 'http://' + proxyOptions.host + ':' + proxyOptions.port
  });
})

And this is the error after some time in node console

Error: socket hang up
    at createHangUpError (http.js:1476:15)
    at Socket.socketOnEnd [as onend] (http.js:1572:23)
    at Socket.g (events.js:180:16)
    at Socket.emit (events.js:117:20)
    at _stream_readable.js:943:16
    at process._tickCallback (node.js:419:13)

Any suggestions about the cause of the problem


回答1:


I think the issue comes from the order of middleware. Using bodyParser before httpProxy will break the requests with JSON body, so httpProxy should be used before bodyParser.

You may want to check this for more info about bodyParser.




回答2:


Use a callback to listen for the error:

proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });

from https://github.com/nodejitsu/node-http-proxy




回答3:


I found the solution to this problem with the help of this issue https://github.com/nodejitsu/node-http-proxy/issues/180#issuecomment-12244852

the solution is to use middleware for proxy before using the bodyparser

code sample

 // use middleware first 
app.post('/solr/*',function(req, res) {
  console.log('POST REQUEST')
  //res.end();
   proxy.web(req, res, {
     target: 'http://' + proxyOptions.host + ':' + proxyOptions.port
   });
})
app.use(logger('dev'));
// use bodyparser after that
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


来源:https://stackoverflow.com/questions/26632854/socket-hangup-while-posting-request-to-node-http-proxy-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!