我正在尝试遵循 Ember 入门指南并构建 TodoMVC 应用程序,但使用带有 Rails 的 Ember-CLI 作为后端。不幸的是,我遇到了跨站点域的问题。我收到此错误消息,并尝试执行发布请求:
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.
在 Rails 一侧,我安装了 Rack Cors。我已将它添加到我的 Gemfile 中:
gem 'rack-cors', :require => 'rack/cors'
在我的application.rb
文件中,我有:
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
这是我的控制器:
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
在我的 Ember 应用程序中,app/adapters/application.js
我有:
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'http://localhost:3000/api'
});