简体   繁体   中英

Setup Node.js HTTPS to work with HAPROXY

I'm trying to make my nodejs app to communicate with HAPROXY via https. The idea is that nodejs sends message to haproxy via https, haproxy routes message forward.

I used request.js library and all worked fine, but now I need to perform this task without any libraries. The scenario is following. If environment variable is 1, I should use HTTP, in other cases -HTTPS. The problem is that when I use https and haproxy, I get "Socket hangup error", but everything works fine with request.js. Here is my code.

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

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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