I’m currently building a cross platform mobile application using cordova / phonegap for the app and express for the server. There’s a web interface, but also data can be retrieved in json format from the server by the mobile app.
Getting server data with Cordova
It’s actually easy to get data from a server from within your cordova application, you don’t even need to worry about cross domain requests. Simply add this to your config.xml (which is now the default) to set up cordova correctly:
Then in my express node app, I do something like this:
Although a little long winded in the controller route code (or action method, if you like, for you C# junkies) it works just fine when the mobile app loads the JSON data from the server using get http requests.
The issue is, I do my initial app development in Chrome…
JSONP to the rescue
JSONP is a hack around doing cross domain get requests but requires the cooperation of the server to succeed. Unfortunately, you can’t request random websites data (client-side) using JSONP. We need to set some config in the express app and do things slightly differently (this isn’t very well documented).
Setting up express
When configuring express, you need to set an additional property:
In your route code
Things get simplier:
That’s it, you’re done! You can happily make JSONP requests to your server.
Wasn’t hard was it? Shame they don’t make it this obvious in the documentation.
Go and make yourself a coffee, you deserve it.