[英]Setup Node.js HTTPS to work with HAPROXY
我正在尝试使我的nodejs应用程序通过https与HAPROXY进行通信。 这个想法是nodejs通过https向haproxy发送消息,haproxy路由消息转发。
我使用了request.js库,并且一切正常,但是现在我需要在没有任何库的情况下执行此任务。 该场景如下。 如果环境变量为1,则应该使用HTTP,在其他情况下,则应使用HTTPS。 问题是,当我使用https和haproxy时,出现“套接字挂断错误”,但对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`);
}
});
通过将content-length标头添加到options.headers中,可以解决此问题。
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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.