Mongoose Can't Connect Without Internet

2019-01-12 03:29发布

问题:

I have my MongoDB server running on localhost:27017, and while I can usually run my Node.js app fine, when I disconnect from the internet Mongoose throws the error

Error: failed to connect to [localhost:27017]

Note that I can still connect to the MongoDB server from the Mongo shell client. Also, if I start up my app first and then lose internet connection, my app can access the database fine offline. So why can't it start up without internet?

EDIT: here is the error in full

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: failed to connect to [localhost:27017]
    at null.<anonymous> (<My App>\node_modules\mongoose\
node_modules\mongodb\lib\mongodb\connection\server.js:555:74)
    at emit (events.js:118:17)
    at null.<anonymous> (<My App>\node_modules\mongoose\
node_modules\mongodb\lib\mongodb\connection\connection_pool.js:156:15)
    at emit (events.js:110:17)
    at Socket.<anonymous> (<My App>\node_modules\mongoos
e\node_modules\mongodb\lib\mongodb\connection\connection.js:534:10)
    at Socket.emit (events.js:107:17)
    at net.js:923:16
    at process._tickCallback (node.js:355:11)
[nodemon] app crashed - waiting for file changes before starting...

Edit: wording

回答1:

Use 127.0.0.1 instead of localhost. By turning off your wifi interface the OS is no longer able to resolve localhost.



回答2:

Consider node-offline-localhost.

Add the following before the breaking code:

require('node-offline-localhost').always();

And it just works (hopefully), at least until RFC 3493 gets fixed.

Full disclosure: I authored this package to streamline https in my dev environment when offline.