Wednesday, December 24, 2014

Cross domain requests in tomcat

I had a strange problem in Tomcat. Everything worked fine when running my webapp on localhost, but when I uploaded it to the server on xxxx.net the call to connect with the Mongo database failed with a mysterious timeout error when opening a socket. But all seemed fine. I could access mongo through the commandline. I could even copy exactly the same instructions in Java and run a local test app that connected to the database flawlessly. The problem was too subtle for me. My test app set up the database connection via localhost, but the webapp used the current host name, which was xxxx.net. So this became a cross-domain request and was refused. All I had to do was change my openConnection call in the Java driver to use localhost and all was fine. A genuine 'gotcha!'

Here's the code that screws up: (you need the mongo driver jar in the classpath)

No comments:

Post a Comment