Jquery: $.getJSON with different url port
ajax, javascript, jquery, json
Solution
The Same Origin Policy prevents JavaScript scripts from making HTTP requests to different domains. For the purposes of SOP, a URL with the same hostname but different ports (as is the case here) is still considered to be a different domain, and hence requests are not permitted.
What typically happens in such cases is that the browser actually does make the request over the network, but drops the response and sends an error result to the JavaScript.
To fix this, you'll need to implement Cross-Origin Resource Sharing on the `localhost:3001` service. In a nutshell, this entails adding a `Access-Control-Allow-Origin` header to responses listing the domains which are permitted to make cross-domain requests to the service. That is, in this case adding a `Access-Control-Allow-Origin: localhost:3000` header to the response from the `localhost:3001` service should allow things to work as you expect.
Incidentally, this is why the browser makes the request but drops the result: it needs to request the headers from the server in order to determine whether the JavaScript is allowed to make the request or not (i.e. it needs to check if there's a `Access-Control-Allow-Origin` header in the response). Why a `HEAD` request isn't sufficient, I don't know.
The other alternative is to use JSONP. This is potentially simpler to implement on the server side, but has the disadvantages of only working for `GET` requests, and requiring slightly trickier coding on the client side.
Problem
I am trying to use `$.getJSON` with a local app calling another local app on a different port. For example my app is running on `localhost:3000`, but I want to make a `$.getJSON` call to another app running on `localhost:3001`, in firebug it returns red with a 200 response, but with no data in the response. Is there a way to do this? I tried this.... ``` $.getJSON('http://localhost:3001/dashboard/widgets/marketing_efficiency_gauge.json', { key: 'value' }, function(data){ alert(data) }); ``` Edit: for clarity there are two rails apps involved one on localhost:3000 another on localhost:3001 Second edit: here is the json response for localhost:3001 when I hit it with a browser (say firefox) https://gist.github.com/willfults/7665299