【发布时间】:2015-05-21 06:21:32
【问题描述】:
我有一个只读 API,它在本地与 Vagrant 设置配合得很好。在我的 Heroku 应用上,每个 API 请求都因 CORS 错误而被拒绝:“请求的资源上不存在 'Access-Control-Allow-Origin' 标头。因此不允许访问 Origin 'null'。”
在我的 API 的基类中,我有以下设置标题:
module API
class Base < Grape::API
before do
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
end
mount API::V1::Base
end
end
我怀疑这个 before 调用没有被触发 - 如果我在其中使用 puts 语句,则该语句不会与其余输出一起出现在我的控制台中。
我很茫然。希望有人对此有一些经验。谢谢。
编辑:我也关注了Grape's CORS instructions,但得到了相同的结果。
成功。我使用了rack-cors gem 和以下:
#application.rb
config.middleware.use Rack::Cors do
allow do
origins '*'
# location of your API
resource '/api/*', :headers => :any, :methods => [:get, :post, :options, :put]
end
end
【问题讨论】:
标签: ruby-on-rails api heroku cors