这个错误是Node.js应用程序中常见的网络连接问题,表示DNS解析失败。具体来说:
getaddrinfo
:Node.js中用于解析主机名的底层函数ENOTFOUND
:错误代码,表示无法找到指定的主机名localhost
:尝试解析的主机名当仅在连接WiFi时出现此错误,可能有以下原因:
// 将
const url = 'http://localhost:3000';
// 改为
const url = 'http://127.0.0.1:3000';
在终端中检查hosts文件内容:
# Windows
type C:\Windows\System32\drivers\etc\hosts
# macOS/Linux
cat /etc/hosts
确保包含以下行:
127.0.0.1 localhost
::1 localhost
// 在Node.js中检查代理设置
console.log(process.env.HTTP_PROXY);
console.log(process.env.HTTPS_PROXY);
const { setDefaultResultOrder } = require('dns');
setDefaultResultOrder('ipv4first');
确保URL包含协议:
// 错误写法
const url = 'localhost:3000';
// 正确写法
const url = 'http://localhost:3000';
try {
// 网络请求代码
} catch (err) {
if (err.code === 'ENOTFOUND') {
console.error('DNS解析失败,尝试使用127.0.0.1');
// 回退到IP地址
}
}
{
"scripts": {
"prestart": "node check-dns.js"
}
}
const HOST = process.env.HOST || 'localhost';
这种问题常见于:
通过以上方法,您应该能够解决WiFi环境下localhost解析失败的问题。
没有搜到相关的文章