nodejs http.request方法没有响应,并且回调没有错误

时间:2019-06-11 13:58:59

标签: node.js express networking cpanel firewall

我想对在同一主机上另一个端口上运行的REST API进行API调用。 http.request方法在localhost上可以正常运行,但在生产环境中则无法正常工作,并且不返回错误。

但是,当在生产环境中对外部主机进行API调用时,此方法很好用。

  • 托管:Cpanel服务器(版本80)
  • 操作系统:Centos7
  • Nodejs:v10.15.3
  • 框架:快速

代码:

var header = { hostname: url,
    port: 80,
    path: path_info,
   method: 'GET',
   timeout: 5000,
   headers:
   { 
     'Content-Type': 'application/json',
     'Accept-Encoding': 'gzip,deflate,br',
     Authorization: string }
   };

    var http = require('http');
    var zlib = require('zlib');
    console.log('REQUEST');
    var api_req = http.request(header, function(api_res) {
        console.log('RESPONSE');
        let data = [];
            var content_response = '';
            if (api_res.headers['content-encoding'] && api_res.headers['content-encoding'] != '') {
                switch (api_res.headers['content-encoding']) {
                    case 'gzip': content_response = zlib.createGunzip();
                        api_res.pipe(content_response);
                        break;
                    case 'deflate': content_response = zlib.createDeflate();
                        api_res.pipe(content_response);
                        break;
                    default: content_response = zlib.createUnzip();
                        api_res.pipe(content_response);
                        break;
                }
            } else {
                content_response = api_res;
            }

            content_response.on('data', (chunk) => {
                data.push(chunk);
            }).on('end', () => {
                console.log(Buffer.concat(data).toString('utf8'));
            }).on('error', (e) => {
                console.log(e);
            });
    });
    api_req.end();

1 个答案:

答案 0 :(得分:0)

问题出在防火墙上。

由于它是经过防火墙NAT的服务器,因此我们需要添加本地主机条目以使内部连接正常工作。