[英]How to set access-control-allow-origin in webrick under rails?
我編寫了一個小型 Rails 應用程序,通過 xmlhttprequests 將內容提供給另一個站點,這些站點將從另一個域運行(不可能讓它們在同一台服務器上運行)。 我知道我需要在我的 rails 服務器上設置 access-control-allow-origin 以允許請求的網頁訪問此材料。
如何使用 Apache 執行此操作似乎有據可查,這可能是我部署站點后將使用的服務器。 雖然我正在開發,但我希望只使用 webrick,就像我習慣使用 Rails 一樣。 有沒有辦法配置 webrick 以在 rails 中提供適當的 http 標頭?
Rails 4 (http://edgeguides.rubyonrails.org/security.html#default-headers )
在 config/application.rb 中:
config.action_dispatch.default_headers.merge!({
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => '*'
})
導軌 3.1
class ApplicationController < ActionController::Base
protect_from_forgery
after_filter :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Request-Method'] = '*'
end
end
如果您使用的是 Rails 2,只需將其添加到您的應用程序控制器中即可。
before_filter :set_access
def set_access
@response.headers["Access-Control-Allow-Origin"] = "*"
end
顯然,將"*"
更改為不那么開放的內容將是一個好主意。
Rails 3.1 - 使用控制器 after_filter 對我不起作用,所以我添加了一個自定義中間件:
在 app/middleware/cors_middleware.rb 中:
# For icons to work in Firefox with CDN
class CorsMiddleware
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
cors_headers = headers.merge({
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => '*'
})
[status, cors_headers, body]
end
end
在 config/application.rb 中:
require File.join(Rails.root, "app", "middleware", "cors_middleware")
config.middleware.insert_before ActionDispatch::Static, CorsMiddleware # Need it early in the chain to work for assets
導軌 2.3.8
before_filter :allow_cross_domain_access
def allow_cross_domain_access
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "*"
end
如果您希望將解決方案作為 Rack 中間件 gem: https : //github.com/cyu/rack-cors
接受的答案有一些變化對我有用。 展示新答案比展示新答案更容易
skip_before_action :verify_authenticity_token
before_action :set_access
def set_access
headers["Access-Control-Allow-Origin"] = "*"
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.