Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access-Control-Allow-Origin issues

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!

like image 668
dennismonsewicz Avatar asked Aug 18 '11 20:08

dennismonsewicz


People also ask

How do I fix Access-Control allow origin?

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.

Is it safe to use Access-Control allow origin?

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.

What happens if Access-Control allow origin is not set?

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.

How do you fix credential is not supported if the CORS header Access-Control allow origin is *?

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.


1 Answers

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!

like image 140
Norman Joyner Avatar answered Oct 15 '22 20:10

Norman Joyner