我试图让我的nodejs应用程序通过https与HAPROXY进行通信。想法是nodejs通过https向haproxy发送消息,haproxy路由消息转发。
我使用了request.js库并且一切正常,但是现在我需要在没有任何库的情况下执行此任务。该方案如下。如果环境变量是1,我应该使用HTTP,在其他情况下-HTTPS。问题是,当我使用https和haproxy时,我得到" Socket挂起错误",但是一切都可以正常处理request.js。这是我的代码。
const protocol = process.env.NODE_ENV === 1 ? require('http') : require('https');
然后我配置HTTPS
this.api = url.parse(app.get('API_HAPROXY'));
this.options = {
port: this.api.port,
hostname: this.api.hostname,
path: '/api/report',
method: 'POST',
headers: {
"Content-Type": "application/json",
},
rejectUnauthorized: false,
requestCert: true,
agent: false
};
因为我不想使用ca来验证ssh密钥,所以我使用NODE_TLS_REJECT_UNAUTHORIZED=0
reportData(json) {
const req = protocol.request(this.options, (res) => {
res.on('error', (err) => {
this.logger.error(`Failed to report ${err.message}`)
})
});
req.write(JSON.stringify(json));
req.end();
req.on('error', (err) => {
this.logger.error(`Failed to report ${err.message}`);
});
}
在这种情况下,我在使用HTTPS
时出现套接字挂起错误这是我的请求配置
request({
uri: `${this.api}/api/report`,
method: 'POST',
json,
}, (err, response) => {
if (err || response.statusCode !== 200) {
this.logger.error(`Failed to report : ${err ? err.message : response.statusCode}`);
} else {
this.logger.info(`Report was sent`);
}
});
答案 0 :(得分:0)
通过向options.headers添加content-length标头来解决此问题。
this.api = url.parse(app.get('API_HAPROXY')); this.options = {
port: this.api.port,
hostname: this.api.hostname,
path: '/api/report',
method: 'POST',
headers: {
"Content-Type": "application/json",
"Content-Length: <calculated length of the object you want to send in bytes >
},
rejectUnauthorized: false,
requestCert: true,
agent: false
};