I’ve been working more and more with nodejs and have to say I am really loving how easy it’s been to get to grips with. I’ll be posting up more about how I’m using node and the problems I’m using it to solve over the coming weeks. However I wanted to illustrate just how simple it is do something that would be more work in other languages such as PHP.
So here’s a quick example I created that illustrates how to make a simple JSONP call to a nodejs + express server.
Here’s the server side code:
and here’s the client side Html code:
To enable jsonp callback support in an ExpressJS application you just have to include the line:
app.enable(“jsonp callback”);
Once you’ve done this you can use the .json() method on the Response object to handle everything for you. So in my example above any HTTP GET request to /foo?cb=myfunction would return myfunction(“hello world”); with the Content-Type header set to text/javascript.
Looks like you need/sometimes need to call res.jsonp(“hello world”); in newer versions.
I could not get the examples I was finding, including this one to work, so I added the p explicitly, and it worked – wheres as before the response was just plain json, even though the request had a callback.
I came here from Google and I just want to point out that the method call should be res.jsonp(). I’m using Express 3.0.0rc4.
Thanks!