AngularJS 和 sinatra CORS
Posted
技术标签:
【中文标题】AngularJS 和 sinatra CORS【英文标题】:AngularJS and sinatra CORS 【发布时间】:2013-12-03 18:50:23 【问题描述】:我正在尝试使用 AngularJS 发帖
$http.post('http://localhost:9393/doRegister',$scope.newUser).success (data)=>
alert data
到一个 sinatra 控制器
post '/doRegister' do
data = request.body.read
return data.password
end
我对 CORS 使用了以下配置
#CORS enable
before do
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Headers'] = 'accept, authorization, origin'
end
options '*' do
response.headers['Allow'] = 'HEAD,GET,PUT,DELETE,OPTIONS,POST'
# Needed for AngularJS
response.headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept'
end
但我仍然从 chrome 收到以下错误
XMLHttpRequest cannot load http://localhost:9393/doRegister. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4567' is therefore not allowed access.
当我尝试调试应用程序时,控制台显示:
W, [2013-11-20T01:39:01.778466 #3716] WARN -- : attack prevented by Rack::Protection::HttpOrigin
127.0.0.1 - - [20/Nov/2013 01:39:01] "POST /doRegister HTTP/1.1" 403 - 0.0016
我尝试使用以下,cors_enable gem,rack/cors gem 我尝试使用以下选项禁用机架保护
use Rack::Protection::HttpOrigin, :origin_whitelist => ['*']
set :protection, :origin_whitelist => ['http://localhost:5445']
set :protection, :except => :frame_options
set :protection, :except => :json_csrf
set :protection, :except => :http_origin
我没有想法,请指教。
【问题讨论】:
你成功了吗? 【参考方案1】:sinatra-cross_origin 会有所帮助。
要安装它,请运行以下命令:gem install sinatra-cross_origin。
为所有路由启用跨源请求:
require 'sinatra'
require 'sinatra/cross_origin'
configure do
enable :cross_origin
end
然后在路线中添加这些行
cross_origin :allow_origin => '*',
:allow_methods => [:get],
:allow_credentials => false,
:max_age => "60"
例子:
get '/custom' do
cross_origin :allow_origin => 'http://example.com',
:allow_methods => [:get],
:allow_credentials => false,
:max_age => "60"
"My custom cross origin response"
end
更多详情您可以点击此链接:sinatra-cross_origin
【讨论】:
【参考方案2】:我在尝试配置 sinatra-cross_origin
时遇到了一些麻烦,但我设法使用 rack-cors gem 使其工作。安装它并将其添加到您的config.ru
require 'rack/cors'
use Rack::Cors do
allow do
origins '*' # 'localhost:3000', 'localhost:8080', '0.0.0.0:3000', '127.0.0.1:3000',
resource '*', headers: :any, methods: [:get, :post, :delete, :put, :patch, :options, :head]
end
end
【讨论】:
以上是关于AngularJS 和 sinatra CORS的主要内容,如果未能解决你的问题,请参考以下文章
在 Sinatra 和 Rails 之间共享 Yaml 配置文件