【问题标题】:Setup Node.js HTTPS to work with HAPROXY设置 Node.js HTTPS 以使用 HAPROXY
【发布时间】:2016-12-17 15:42:41
【问题描述】:

我正在尝试让我的 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`);
    }
});

【问题讨论】:

  • 代理 url 是否包含端口?
  • process.env.NODE_ENV === 1 我觉得 env 值是字符串,所以这总是错误的
  • 是的。它包含。它适用于请求。问题不在环境中,因为它使用https,我已经检查过了

标签: javascript node.js sockets haproxy requestjs


【解决方案1】:

已通过将 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
 };

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 2017-08-05
    • 2012-03-23
    • 2019-06-16
    • 1970-01-01
    • 2019-06-07
    • 2012-12-18
    • 1970-01-01
    相关资源
    最近更新 更多