Node.js で Web アプリケーションを書いていて、別の Web サーバー (HTTPS) からデータを取ってきたくてこんなコードを書いた。
route/index.js
var https = require('https');
...
var request_options = {
host : 'xxx.yyy.zzz.nnn',
port : 'mmmm',
path : '/hogehoge',
method : 'GET'
};
var request = https.request(request_options, function(response) {
...
};
アクセス先の Web サーバーがテスト用の自己署名証明書を提示してくるもんで、実行するとこうなる。
events.js:141
throw er; // Unhandled 'error' event
^
Error: self signed certificate
at Error (native)
at TLSSocket.<anonymous> (_tls_wrap.js:1022:38)
at emitNone (events.js:67:13)
at TLSSocket.emit (events.js:166:7)
at TLSSocket._init.ssl.onclienthello.ssl.oncertcb.TLSSocket._finishInit (_tls_wrap.js:586:8)
at TLSWrap.ssl.onclienthello.ssl.oncertcb.ssl.onnewsession.ssl.onhandshakedone (_tls_wrap.js:428:38)
自己署名なんで検証に失敗するわけだ…。
https://nodejs.org/api/https.html#https_https_request_options_callback を読んでいると、rejectUnauthorized
オプションが見つかった。
テストなのでとりあえずつながればいいので、これの値を false として request_options
に追加してみるが結果変わらず。
上のリンク先をよく読むと気づくのだが、こう書いてある。
a globalAgent silently ignores these.
書いてもいいけど、globalAgent だと何も言わずに無視されるわけだ。
続きにはこうある。
In order to specify these options, use a custom Agent.
Custom Agent とやらを書けばいいらしい。
書き方はこの引用の続きにあるので、これを参考に書き直してめでたし。