nodejs以递归模式的http请求

时间:2016-07-28 21:20:32

标签: node.js https cron ssl-certificate

您好我正在尝试按计划进行http呼叫。计划中的第一次出现在第二次出现时工作正常我得到空对象并且未定义。

var https = require('https');
 var schedule = require('node-schedule');
 var rule = new schedule.RecurrenceRule();
 rule.second = 10;
schedule.scheduleJob(rule, function(){

  var options = {
    host: 'google.co.uk',
    method: 'get',
    path: '/'
};

var req = https.request(options, function(res) {
    // some code
    console.log('Expity date is ' + res.socket.getPeerCertificate(true).valid_to);


});
req.end();
});

输出如下:为什么在作为时间表运行时不起作用?

Expity date is Oct  5 13:16:00 2016 GMT
Expity date is undefined

1 个答案:

答案 0 :(得分:0)

经过一些痛苦的调试后发现请求对象使用代理来启动连接并使用先前建立的连接,并且不再请求证书。因此行为。要解决此问题,请使用“agent”作为选项并将其设置为false。

下面的修改代码。

var https = require('https');
 var schedule = require('node-schedule');
 var rule = new schedule.RecurrenceRule();
 rule.second = 10;
schedule.scheduleJob(rule, function(){

 var options = {
    host: 'online.hmrc.gov.uk',
    method: 'get',
    path: '/',
    agent: 'false' // essential to close down previous conncetion pools and make a fresh call.
};
options.agent = new https.Agent(options); // Initialise a new agent with options as its parameters.
var req = https.request(options, function(res) {
    // some code
    console.log('Expity date is ' + res.socket.getPeerCertificate(true).valid_to);


});
req.end();
});