Node.js代理服务器套接字挂断 [英] Node.js proxy server socket hang up
问题描述
我将Node.js用作代理服务器,但无法摆脱以下错误.任何熟悉NodeJS的人都可以协助寻找解决方案.每次发生这种情况时,我都必须重新启动.js代理.
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)
在此先感谢您的帮助.
推荐答案
因此,在我的情况下,套接字挂起与post请求有关,而get请求在post man和浏览器中均能正常工作
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
从第一台服务器发送的发布请求正文是原始JSON,因此代理服务器将无法解析该正文.
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);
}
}
这篇关于Node.js代理服务器套接字挂断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!