我试图仅针对选项请求覆盖资源的路由。我需要这个来正确获取跨域照片上传请求。
路线.rb
map.resources :photos
map.connect '/photos', :controller => 'photos',
:action => 'options_stuff', :conditions => {:method => :options }
照片控制器.rb
def options_stuff
puts "got to options@!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
set_access_control_headers
head :ok
render :nothing => true, :status => 200
end
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Max-Age'] = '1000'
headers['Access-Control-Allow-Headers'] = '*,x-requested-with'
puts "headers are #{headers}"
end
但是它永远不会到达我需要的控制器。我究竟做错了什么?
顺便说一句,我正在关注以下两篇关于如何做到这一点的文章:http: //www.codeodor.com/index.cfm/2011/7/26/Responding-to-the-OPTIONS-HTTP-method-request-in -Rails-Getting-around-the-Same-Origin-Policy/3387
https://gist.github.com/832700
更新 在经历了很多痛苦和痛苦之后,我放弃了控制器的想法,尽管它确实像答案所暗示的那样工作。相反,有人建议使用 before 过滤器,如下所示:
设置前
before_filter :set_access_control_headers, :only => [:index]
def set_access_control_headers
if !request.put? && !request.post? && !request.delete? && !request.get?
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Max-Age'] = '1000'
headers['Access-Control-Allow-Headers'] = '*,x-requested-with'
puts "headers are #{headers}"
render :nothing => true, :status => 200
return false
end
end