15

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

woojoo666
  • 7,801
  • 7
  • 45
  • 57

2 Answers2

31

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

PeterVC
  • 4,574
  • 2
  • 16
  • 14
  • Just wondering, why would mongoose not be able to resolve localhost while offline if my browser can? – woojoo666 Mar 21 '15 at 20:36
  • 1
    I suspect your using Windows? This may help [explain](http://stackoverflow.com/questions/6997442/nodejs-cannot-resolve-localhost-on-windows). – PeterVC Mar 21 '15 at 21:14
  • Hi all, I've an offline laptop, not connected to any router. I didn't have IP address so I've used Windows Loopback Adapter. https://technet.microsoft.com/en-us/library/cc708322(v=ws.10).aspx but when I run mongo.exe I get Failed to connect 127.0.0.1. how can I configure mongo.exe if the process is not runing at all? – azulay7 Jan 11 '18 at 13:58
0

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.

Yaacov
  • 185
  • 4