Ember CLI allows you to separate the client-side code from the server-side. During development your Ember app can run on one server by typing:
And your Rails API can run on another:
But the browser doesn’t allow you to make AJAX requests to a different server, you will get the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.
But there is a thing called Cross Origin Resource Sharing or CORS which allows you to do it in modern browsers as longs as the server is setup correctly. So below I’ve set it up for Rails in development mode only:
group :development do gem 'rack-cors', require: 'rack/cors' end
Then type the following in your Rails project:
And then add the following to
config/environments/development.rb and restart the Rails server.
Webapp::Application.configure do config.middleware.use Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: [:get, :post, :put, :delete, : options] end end end
So for each request the browser sends an OPTIONS request first and the server returns a response with some extra headers. The browser is then able to make the original request.