简体   繁体   English

设置Node.js HTTPS以与HAPROXY一起使用

[英]Setup Node.js HTTPS to work with HAPROXY

I'm trying to make my nodejs app to communicate with HAPROXY via https. 我正在尝试使我的nodejs应用程序通过https与HAPROXY进行通信。 The idea is that nodejs sends message to haproxy via https, haproxy routes message forward. 这个想法是nodejs通过https向haproxy发送消息,haproxy路由消息转发。

I used request.js library and all worked fine, but now I need to perform this task without any libraries. 我使用了request.js库,并且一切正常,但是现在我需要在没有任何库的情况下执行此任务。 The scenario is following. 该场景如下。 If environment variable is 1, I should use HTTP, in other cases -HTTPS. 如果环境变量为1,则应该使用HTTP,在其他情况下,则应使用HTTPS。 The problem is that when I use https and haproxy, I get "Socket hangup error", but everything works fine with request.js. 问题是,当我使用https和haproxy时,出现“套接字挂断错误”,但对request.js一切正常。 Here is my code. 这是我的代码。

const protocol = process.env.NODE_ENV === 1 ? require('http') : require('https');

then I configure 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
};

Because I don't want to use ca to validate ssh keys I use NODE_TLS_REJECT_UNAUTHORIZED=0 因为我不想使用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}`);
    });
}

In this case I get socket hangup error while using HTTPS 在这种情况下,使用HTTPS时出现套接字挂断错误

Here is my request configuration 这是我的请求配置

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`);
    }
});

The issue was fixed by adding content-length header to the options.headers. 通过将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM