0

I'm developing a very simple angular 2 app using the angular2/http module to access a rails resource. I'm running both a node development server and the rails development server. The issue I'm having is getting around the same origin policy restrictions on an ajax call to a rails backend.

error:

XMLHttpRequest cannot load http://localhost:3000/people.
Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.

My servers are on

http://localhost:8080 //node
http://localhost:3000 //rails

I need clarification how this works:

  1. Will these services clash if I run them on the same port?
  2. If you have to run on different domains, how do you do this securely?
  3. How do admins handle this in production modes when servers are almost certainly going to be on a different port/domain?
1
  • 1
    This is caused by the browsers, they don't allow you to do requests between different domains, in order to let the browser know that it is ok, you need to set a Header to every response from your rails server telling the browser which origins are allowed. If you add this: Access-Control-Allow-Origin: * to every response, you are telling the browser that anyone can make requests to your server through a different domain. See: developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS and gist.github.com/dhoelzgen/cd7126b8652229d32eb4 Commented Jan 27, 2016 at 20:19

1 Answer 1

6

Langley's second link turned up a great Rails module to manage CORS.

Github rack-cors Gem

Simply include it in your Gemfile and add the following to your config/application.rb

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.