Fetching JSON data with JSONP
JSONP or JSON with padding is a mechanism of making cross-domain requests by taking advantage of the <script>
tag. AJAX transport is done by simply setting the src
attribute on a script
element or adding the element itself if not present. The browser will do an HTTP request to download the URL specified, and that is not subject to the same origin policy, meaning that we can use it to get data from servers that are not under our control. In this recipe, we will create a simple JSONP request, and a simple server to back that up.
Getting ready
We will make a simplified implementation of the server we used in previous examples, so we need Node.js and restify (http://mcavage.github.io/node-restify/) installed either via definition of package.json
or a simple install. For working with Node.js, please refer to Appendix A, Installing Node.js and Using npm.
How to do it...
First, we will create a simple route handler that will return a JSON object:
function respond...