JSONP in Express/Node.js

Express JS

Express is a web application framework that facilitates the rapid and scalable development of node apps.

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:

config.xml
1
2
3
<widget>
<access origin="*" />
</widget>

Then in my express node app, I do something like this:

Express route "/test"
1
2
3
4
5
app.get("/test", function(req, res){
res.writeHead(200, { "Content-Type": "application/json" });
res.write(JSON.stringify({ "my": "object" }));
res.end();
});

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:

Configuring express
1
app.set("jsonp callback", true);

In your route code

Things get simplier:

Express route "/test"
1
2
3
app.get("/test", function(req, res){
res.jsonp({ "my": "object" });
});

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.