我在节点v4.1.2上使用节点包RequestJS v2.65.0
我正试图从某些网站read the SSL certificate(例如GitHub.com)。 以前在节点0.12 上工作。但是,在节点4.2.1上,getPeerCertificate()
返回null
。
例如:
request({
url: 'https://github.com'
}, function (err, res, body) {
console.log('err:', err)
console.log('peerCertificate:',res.req.connection.getPeerCertificate());
console.log('authorized:',res.req.connection.authorized);
console.log('authorizationError:',res.req.connection.authorizationError);
});
将打印出来
err: null
peerCertificate: null
authorized: true
authorizationError: null
即。安全连接已建立,但证书为空。
根据我的(基本)理解,如果连接被授权,则应该有对等证书。
我尝试过很多SSL网站,结果是一样的。请求中是否有选项,Node 4存在错误,或者我对SSL/TLS works in node的方式存在误解?
答案 0 :(得分:3)
我认为您的问题是因为getPeerCertificate()
只会在连接处于connected
状态时输出任何内容,但是当您收到回复时,它可能已经太晚了。
如果您希望输出getPeerCertificate
,则应该单独在TLS级别执行此操作:
const socket = require('tls').connect(443, "github.com", () => {
console.log('client connected',
socket.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(socket);
process.stdin.resume();
});
重要! :不要将协议放在URL中。相反,请使用require(' url')。parse(yourURL).hostname作为目标。
此处有更多信息和示例:https://nodejs.org/api/tls.html#tls_tls_connect_port_host_options_callback
答案 1 :(得分:1)
@nembleton对于这种情况发生的原因是正确的。这是https://github.com/request/request/issues/1867
的问题您可以坚持使用Request并使用其流API,而不是简化为原始TLS套接字。如果您正在利用其他会使低级别连接更复杂的请求功能(例如,通过HTTPS代理),这种方法特别有用。
原始问题中的代码段变为:
request({
url: 'https://github.com'
})
.on('error', function(err) {
console.log('err:', err);
})
.on('response', function (res) {
console.log('peerCertificate:',res.socket.getPeerCertificate());
console.log('authorized:',res.socket.authorized);
console.log('authorizationError:',res.socket.authorizationError);
});
(为了简洁/直接,我使用了res.socket
而不是res.req.connection
,但两种方法都有效。)