I have two local rails apps that I would like to talk to each other for testing purposes... one is running on port 3000 and the other on 9292.
But when I make an ajax request from localhost:3000 to localhost:9292 I keep getting this issue:
Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
Any idea on how to fix this?
I am using a simple Sinatra app to receive (for testing purposes ONLY) JSON requests. Below is how I got two rails apps talking to each other on localhost (one on port 3000 and the other on port 9292)
Working Code
before do
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, X-CSRF-Token'
end
after do
headers['Access-Control-Allow-Origin'] = 'http://localhost:3000/'
end
Hope this helps!
If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.
Access-Control-Allow-Origin: * is totally safe to add to any resource, unless that resource contains private data protected by something other than standard credentials. Standard credentials are cookies, HTTP basic auth, and TLS client certificates.
So, What is This Error Then? This error occurs when a script on your website/web app attempts to make a request to a resource that isn't configured to accept requests coming from code that doesn't come from the same (sub)domain, thus violating the Same-Origin policy.
To correct this problem on the client side, ensure that the credentials flag's value is false when issuing your CORS request. If the request is being issued using XMLHttpRequest , make sure you're not setting withCredentials to true . If using Server-sent events, make sure EventSource.
Cross-domain AJAX is generally not allowed for security reasons. JSONP is an option if you are able to use it. If not, you can use something like flXHR to get around this restriction.
Best of luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With