【发布时间】:2011-10-29 21:54:20
【问题描述】:
如何设置 Sinatra 以便在公用文件夹中保存静态文件 与响应 Access-Control-Allow-Origin = "*" 一起返回?
【问题讨论】:
如何设置 Sinatra 以便在公用文件夹中保存静态文件 与响应 Access-Control-Allow-Origin = "*" 一起返回?
【问题讨论】:
在这里查看这个问题:Sinatra OPTIONS HTTP Verb。它现在已在 sinatra 中实现,因此您不必绕开它。
如果这没有帮助,请查看这篇博文:Cross Origin Resource Sharing with Sinatra,以及它在 github 上的 repo:sinatra-corss_origin
虽然最简单的方法应该只是添加以下内容:
response['Access-Control-Allow-Origin'] = 'http://whatever.org'
在你的路由返回值之前。
【讨论】:
response,而是headers:headers( "Access-Control-Allow-Origin" => "*" )
get '/' do<new line>response['Access-Control-Allow-Origin'] = '*'<new line>"asdf"<new line>end内
get '/foo' do
headers 'Access-Control-Allow-Origin' => 'http://example.com'
'hello world'
end
还有一个不错的跨域共享扩展:
https://github.com/britg/sinatra-cross_origin
require 'sinatra'
require 'sinatra/cross_origin'
# To enable cross origin requests for all routes:
configure do
enable :cross_origin
end
# To only enable cross origin requests for certain routes:
get '/cross_origin' do
cross_origin
"This is available to cross-origin javascripts"
end
【讨论】:
Access-Control-Allow-Origin 标头显示出来,直到我在我的响应方法中明确添加它,就像@daddz 的回答一样
我是在服务器端执行此操作的,我的文件名为 server.rb:
before do
content_type :json
headers 'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST']
end
【讨论】:
headers "Access-Control-Allow-Origin" => "*" 就允许了 GET 请求。没有尝试其他动词。
此设置适合我:
宝石文件:
# Gemfile
gem 'sinatra'
gem 'sinatra-cross_origin'
Sinatra 应用程序:
# app.rb
require 'sinatra'
require 'sinatra/cross_origin'
class MyApp < Sinatra::Base
set :bind, '0.0.0.0'
configure do
#This is enable cross on the server
enable :cross_origin
end
#This before blocks gets invoked on every request and
#the (*) mark tells your server that share the resource with anyone,
#if you want to share it with specific domain you can mention the domain/s
#by removing the asterisk sign.
before do
response.headers['Access-Control-Allow-Origin'] = '*'
end
# routes...
options "*" do
response.headers["Allow"] = "GET, PUT, POST, DELETE, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Authorization,
Content-Type, Accept, X-User-Email, X-Auth-Token"
response.headers["Access-Control-Allow-Origin"] = "*"
200
end
end
上述选项块向浏览器发送的预检请求发送 200 响应。然后浏览器发出 CORS 请求。为响应此请求,服务器在响应标头中发送 Access-Control-Allow-Origin = *。
如果我们只希望特定域访问资源:
before do
response.headers['Access-Control-Allow-Origin'] = 'http://example.com'
end
【讨论】:
此解决方案适用于我,并且基于对类似问题 How to add "Access-Control-Allow-Origin" headers to API Response in Ruby 的回答
get '/' do
response['Access-Control-Allow-Origin'] = '*'
"asdf" # return "asdf"
end
【讨论】: