Nodejs发送https Post请求时出现socket hang up错误的解决办法汇总

参考nodejs官网发送http post请求的方法,实现了一个模拟post提交的功能。实际使用时报socket hang up错误。

方法一:后来发现是请求头设置的问题,发送选项中需要加上headers字段信息(这个估计也和对方的服务器有关,对于不完成的post请求头,可能被丢弃了)。

完整的代码如下(遇到类型问题的同学可以做个参考):

var querystring = require('querystring')
  , http = require('http');

var data = querystring.stringify({
  info:'hi',
  test:5
});

var opt = {
  hostname:'www.test.com',
  port :9094,
  path:'/perationSqlQuery',
  method: 'POST',
  headers: {   
    'Content-Type':'application/x-www-form-urlencoded',
    'Content-Length': data.length  
  } 
};

var req = http.request(opt, function (res) {  
  res.on('data', function (data) {
    console.log(data.toString());
  });
});
req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});
req.write(data);
req.end();

方法二:https请求库更换成Unirest

let unirest = require('unirest');

function execute_http_request(options, body, callback) {
     let url = 'https://' + options.hostname + options.path;
     console.log('post: ' + url);
     // console.log('headers: ' + JSON.stringify(options.headers));
     unirest.post(url).strictSSL(false).headers(options.headers)
         .send(body).end((response) => {
             console.log('code: ' + response.code + ', body: ' + response.body);
             callback(null, response.body);
         });
}

简单替换掉之前的代码之后,发现第二次访问是可以正常返回结果的,但是后面的某一次还是有很大的几率会出现无返回值的情况.
后来查看官方的API手册发现了这个方法timeout(),在代码中添加了超时设置以后,竟然正常了,但是会有那么一点点慢,估计是设置的超时时间不合适的缘故吧.

......
unirest.post(url).strictSSL(false).headers(options.headers).timeout(1500)
......

在投入Nodejs开发之后,发现Nodejs上的坑绝不比Android上的少,有些是前人踩过的,有些是没有踩过的,不管有没有踩过,遇到后总要把它填上,本来想把自己这两个月开发过程中遇到的问题总结一下,但是一旦忙起来真是是根本停不下来,算了,还是看心情吧...

用了一段时间以后,发现虽然没有了socket hang up的问题,但是服务器返回的response偶尔会出现undefined的情况,后来看到unirest库也是对request库上层进行的封装,所以理论上完全可以替换为request,经过几分钟的替换,发现效果确实还好,测试的几十次中没有再出现undefined的情况了,代码如下:

let request = require('request');
function execute_http_request(options, body, callback) {

    let o = {
        url: 'https://' + options.hostname + options.path,
        method: 'POST',
        strictSSL: false,
        timeout: 1500,
        headers: options.headers,
        body: body
    };

    // console.log(o);

    request(o, (err, response, body) => {
        if (err) {
            callback(err);
        } else {
            // console.log('response = ' + JSON.stringify(response, null, 4));
            console.log('body = ' + body);
            callback(null, body);
        } 
    });
}
发布了193 篇原创文章 · 获赞 139 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/qappleh/article/details/100992065