Reputation: 11
I am using Node.js as a proxy server and I cannot get rid of the following error. Can anyone familiar with NodeJS assist in finding a solution. Each time this happens I have to restart the .js proxy.
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1264:15)
at CleartextStream.socketCloseListener (http.js:1315:23)
at CleartextStream.EventEmitter.emit (events.js:93:17)
at SecurePair.destroy (tls.js:938:22)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
Thanks in advance for any assistance.
Upvotes: 1
Views: 1621
Reputation: 11
Request should be stringify on proxy request middleware other wise it throw error. BadRequestError: request aborted on source server. on proxy server it was socket hanged up . so solution is to pass the json data in string.
onProxyReq: function onProxyReq(proxyReq: any, req: Request) {
if(req.body) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type','application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
}
Upvotes: 0
Reputation: 97
So in my case the socket hangup was with the post request and the get request worked fine from post man and as well as from browser
The post request body which were sent from 1st server was the raw JSON, so the proxied server will not be able to parse the body.
We need to stringify the body on request, below code will help us to stringify and send the data to proxy server on trigger of request
const proxy = httpProxy.createProxyServer();
proxy.on('proxyReq', proxyRequestHandeler);
proxyRequestHandeler = (proxyReq, req) => {
if(req.body) {
const 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
proxyReq.write(bodyData);
}
}
Upvotes: 1
Reputation: 46
This error happens sometimes, it's normal, because client/server can break connection by himself in a wrong way. You could listen for 'error' event on socket, so you can catch error and don't restart whole process.
Upvotes: 0