我在我的 Windows 机器上安装了一个 mySQL 服务器,我还安装了 WSL,所以我可以在我的 Windows 机器上使用 linux 的所有好东西。我有一个任务是用 express 制作一个 JS api 并连接到数据库,所以我运行我的 mySQL 服务器,一切运行正常,但是当我使用node index.js
从 WSL 启动 JS api 并尝试连接到数据库时,它会抛出一个sql错误
Server running on port 8080 , http://localhost:8080
/mnt/c/Users/ngkil/Documents/VSCode/WebDevAssignment2022/Backend/index.js:43
if (err) { throw err; }
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1195:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
Node.js v18.1.0
如果我从 CMD 运行相同的命令node index.js
,则 api 工作正常
Server running on port 8080 , http://localhost:8080
Connected to database
我不明白我的 mySQL 服务器和 WSL 之间出了什么问题,两者之间存在的唯一交互是我尝试从 WSL 连接到 localhost,这是 unix 问题吗???
这不起作用,因为 WSL2 使用由 Windows 虚拟机平台(Hyper-V 的子集)创建的虚拟网络 (vNIC) 运行。在 WSL2 中,localhost 是 vNIC 的地址。
最简单的解决方案是获取 Windows 的 IP 地址并使用此地址而不是 localhost 连接到数据库。
不幸的是,每次运行 linux 时 IP 都会改变。WSL 将您的 Windows 主机 IP 存储在/etc/resolv.conf
文件中。因此,您可以修改/etc/hosts
以动态映射winhost
到主机 IP。为此,在~/.bashrc
文件末尾添加以下行:
export winhost=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
if [ ! -n "$(grep -P "[[:space:]]winhost" /etc/hosts)" ]; then
printf "%s\t%s\n" "$winhost" "winhost" | sudo tee -a "/etc/hosts"
fi
然后运行:
source ~/.bashrc
现在代替localhost
使用winhost
. 请让我知道这是否对您有所帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句