Node.js报ERR_TLS_CERT_ALTNAME_INVALID错误的解决咨询
我调用了如下函数:
export async function getStaticProps() { const res = await fetch("https://links.papareact.com/pyp"); const exploreData = await res.json(); return { props: { exploreData, }, }; }
但出现了以下服务器错误:
Server Error
FetchError: request to https://jsonkeeper.com/b/4G1G failed, reason: Hostname/IP does not match certificate's altnames: Host: jsonkeeper.com. is not in the cert's altnames: DNS:www.jsonkeeper.com
This error happened while generating the page. Any console logs will be displayed in the terminal window.Call Stack
ClientRequest.
file:///P:/Work/Web%20Development/airbnb-clone/node_modules/next/dist/compiled/node-fetch/index.js (1:65756)
ClientRequest.emit
node:events (527:28)
TLSSocket.socketErrorListener
node:_http_client (454:9)
TLSSocket.emit
node:events (527:28)
emitErrorNT
node:internal/streams/destroy (157:8)
emitErrorCloseNT
node:internal/streams/destroy (122:3)
processTicksAndRejections
node:internal/process/task_queues (83:21)
同时返回错误信息:
type: 'system', errno: 'ERR_TLS_CERT_ALTNAME_INVALID', code: 'ERR_TLS_CERT_ALTNAME_INVALID',
我已安装mkcert,但问题仍未解决,请问该如何处理这个问题?
修正请求域名:错误核心是
jsonkeeper.com的SSL证书仅包含www.jsonkeeper.com的域名,而实际请求的是不带www的版本。你可以直接将跳转后的目标地址改为https://www.jsonkeeper.com/b/4G1G,或者检查links.papareact.com/pyp的跳转逻辑,确保最终请求的是带www的域名。临时禁用证书校验(仅限开发环境):如果是开发阶段急需绕过该问题,可以在fetch请求中添加禁用证书校验的配置,生产环境绝对禁止使用,会引发安全风险。示例代码:
export async function getStaticProps() { const https = require('https'); const agent = new https.Agent({ rejectUnauthorized: false }); const res = await fetch("https://links.papareact.com/pyp", { agent }); const exploreData = await res.json(); return { props: { exploreData, }, }; }
清理DNS缓存与检查hosts文件:本地DNS缓存或hosts文件的错误映射可能导致域名解析异常,尝试清除本地DNS缓存,或者检查hosts文件中是否存在
jsonkeeper.com的错误配置。升级Node.js版本:部分旧版Node.js的TLS证书校验逻辑存在缺陷,升级到最新LTS版本可能解决证书匹配问题。
内容的提问来源于stack exchange,提问作者Jaid Chowdhury

