Error: unable to verify the first certificate
针对此问题,网上大部份的解决方案是绕开证书检测,即用以下方法进行曲线救国:
const https = require('https') const httpsAgent = new https.Agent({ rejectUnauthorized: false }) axios.defaults.httpsAgent = httpsAgent
虽然这样也达到了目的,但是在安全性上大打折扣。如何从根本上解决此问题呢?
也很简单,就是给axios提供目标站点的证书链(we can set ca chain to https.Agent),代码如下:
const https = require('https') const fs = require("fs") const httpsAgent = new https.Agent({ ca: fs.readFileSync(<ca-path>) // ca-path为证书链文件路径,比如:./example.com.crt }) axios.defaults.httpsAgent = httpsAgent接下来的问题是,如何得到证书链文件。我们以example.com为例。(How to get ca-path?)
在chrome中打开https://example.com站点,依次点击地址栏的小锁图标->连接是安全的
点击证书有效旁边的方块图标
打开证书信息面板之后,点击详细信息Tab页
点击导出
选择导出为证书链,保存为本地文件,比如example.com.crt
将example.com.crt文件替换掉ca-path就OK了。(Use 'example.com.crt' to replace ca-path)
类似的问题也会出现在PHP的file_get_contents中(报错信息为file_get_contents(): Failed to enable crypto),
同样也可以用这样的方法解决:
$options = [ 'http' => [ 'header' => 'Content-Type: application/x-www-form-urlencoded', 'method' => 'POST', 'content' => 'a=b&c=d' ], 'ssl' => [ 'verify_peer' => true, 'cafile' => './example.com.crt' // 配置证书链文件路径 ] ]; $url = 'https://example.com/api/xxx'; $context = stream_context_create($options); $resp = file_get_contents($url, false, $context);