[英]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.