Sinatra access-control-allow-origin for sinatra public folder

时间:2011-08-18 15:25:33

标签: html sinatra

如何设置Sinatra以便公共文件夹中的静态文件 返回的是响应Access-Control-Allow-Origin =“*”?

5 个答案:

答案 0 :(得分:17)

在这里查看这个问题:Sinatra OPTIONS HTTP Verb。它现在在sinatra中实现,所以你不必破解它。

如果这有助于查看此博文:Cross Origin Resource Sharing with Sinatra及其在github上的回购:sinatra-corss_origin

虽然最简单的方法应该只需添加:

response['Access-Control-Allow-Origin'] = 'http://whatever.org'

在路线中的返回值之前。

答案 1 :(得分:6)

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

答案 2 :(得分:3)

我在服务器端执行此操作,我的文件名为server.rb:

before do
   content_type :json    
   headers 'Access-Control-Allow-Origin' => '*', 
            'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST']  
end

答案 3 :(得分:0)

此设置对我有用:

宝石文件:

# 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

答案 4 :(得分:-1)

此解决方案对我有效,它基于类似问题How to add "Access-Control-Allow-Origin" headers to API Response in Ruby

的答案
get '/' do
  response['Access-Control-Allow-Origin'] = '*'
  "asdf"  # return "asdf" 
end