我正在嘗試重寫僅用於選項請求的資源路由。我需要這個來正確獲取跨域照片上傳請求。在Rails 2中覆蓋資源路由
的routes.rb
map.resources :photos
map.connect '/photos', :controller => 'photos',
:action => 'options_stuff', :conditions => {:method => :options }
photos_controller.rb
def options_stuff
puts "got to [email protected]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
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_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
行爲的名稱在您的路線中是錯誤的。它不應該是options_stuff? – Ashitaka
謝謝修復。但那不是 –
'在控制器中調試'printf'可能不是實現這一點的最佳方式,但至少你對此感到興奮。 – tadman