2

I'm trying to follow the Ember Getting Started guide and build a TodoMVC app but use Ember-CLI with Rails as a backend. Unfortunately I'm running into an issue with cross site domain stuff. I'm getting this error message with I try and do a post request:

XMLHttpRequest cannot load http://localhost:3000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

On the Rails side I have Rack Cors installed. I have it added to my Gemfile:

gem 'rack-cors', :require => 'rack/cors'

And in my application.rb file I have:

module Todoemberrails
  class Application < Rails::Application
    config.assets.enabled = false

    config.middleware.use Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :put, :delete, :options]
      end
    end
  end
end

And this is my controller:

class Api::TodosController < ApplicationController
  def index
    render json: Todo.all
  end

  def show
    render json: Todo.find(params[:id])
  end

  def create
    todo = Todo.new(todo_params)

    if todo.save
      render json: todo, status: :created
    else
      render json: todo.errors, status: :unprocessed
    end
  end

  private

  def todo_params
    params.require(:todo).permit(:title, :is_completed)
  end
end

And inside of my Ember app in app/adapters/application.js I have:

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  host: 'http://localhost:3000/api'
});
PrestaShopDeveloper
  • 3,110
  • 3
  • 21
  • 30
Blake Erickson
  • 755
  • 1
  • 9
  • 28
  • Why is localhost:4200 sending the request? Are you running the app from there? If so, would changing your host to host: 'localhost:4200/api' help? – Jacquerie Jun 22 '14 at 16:13
  • I'm using Ember-CLI so it is using its own webserver to host the ember app, so no I couldn't change the rails server to localhost:4200 because they can't be running on the same port. – Blake Erickson Jun 22 '14 at 19:43
  • I cannot provide a solution, but if you are stuck I recommend having a look at the `DS.ActiveModelAdapter`. Combined with gem `active_model_serializers` it works flawlessly. – AWM Jun 23 '14 at 14:57

1 Answers1

0

Rails doesn't allow this by default, to prevent Cross Site Scripting.

If you want to allow this accross the board, you can add this to your ApplicationController:

  after_filter :cors_set_access_control_headers

  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin']      = '*'
    headers['Access-Control-Allow-Methods']     = 'POST, GET, OPTIONS'
    headers['Access-Control-Max-Age']           = '1728000'
    headers['Access-Control-Allow-Credentials'] = 'true'
  end

Sounds ok for a getting started with Ember guide, but not for a production app.

Steve Ellis
  • 494
  • 5
  • 13