nodejs请求HTTPS报错:UNABLE_TO_VERIFY_LEAF_SIGNATURE的解决

出现这个错误是因为对方网站的证书不正确导致的。

在请求的时候指定忽略证书验证,即options的rejectUnauthorized参数设置为false

var https = require('https'); 

var options = { 
  hostname: 'encrypted.google.com', 
  port: 443, 
  path: '/', 
  method: 'GET', 
  rejectUnauthorized:false 
}; 

var req = https.request(options, function(res) { 
  console.log("statusCode: ", res.statusCode); 
  console.log("headers: ", res.headers); 

  res.on('data', function(d) { 
    process.stdout.write(d); 
  }); 
}); 
req.end(); 

req.on('error', function(e) { 
  console.error(e); 
});

nodejs官方SDK关于该参数的说明:

rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An 'error'event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default true.

来自:悠游悠游,原文地址:https://play175.com/p/205.html