为什么我的 MongoDB 数据库使用包含 127.0.0.1 的 URL 进行连接,而不是默认使用“localhost”,即使当我尝试使用“localhost”时它不起作用? 这是我得到的错误:
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
{
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 79726509,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\...\connect.js:379:20)
at Socket.<anonymous> (C:\Users\...\connect.js:285:22)
at Object.onceWrapper (node:events:628:26)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
[Symbol(errorLabels)]: Set(1) { 'ResetPool' },
[cause]: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
}
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
Node.js v18.16.0
我尝试禁用公共和专用网络的防火墙,但仍然不起作用。当我替换代码中使用的 URL 中的“localhost”以使用 IP 127.0.0.1 连接到数据库时,数据库似乎已连接。
这似乎是 IPv6 问题。最有可能的是,
localhost
最初被解析为 IPv6 地址 (::1),并且当失败时,node.js 不会再次尝试。当您指定 IPv4 地址 127.0.0.1 时,第一次尝试即可建立连接。