1

我正在尝试使用 rails 3 rest api 创建一个电话间隙应用程序。由于跨域,我必须使用只允许 GET 的 JSONP。但是rails你可以把_method=POST放在表单动作中来覆盖方法

我还需要用我自己的自定义中间件覆盖机架中间件 MehtodOVerride 以允许它。

所以我用以下代码创建了一个 lib/restful_jsonp_middleware.rb

module Rack

class RestfulJsonpMiddleware

  HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS)
  METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
  HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze

  attr_accessor :method_parameter_name

  def initialize(app)
    @app = app
    @method_parameter_name = METHOD_OVERRIDE_PARAM_KEY
  end

  # We check if the method parameter is in the request
  # and set up the request to allow the execution of the
  # overwritten HTTP method
  def call(env)
    req = Request.new(env)
    method = req.params[@method_parameter_name]
    method = method.to_s.upcase
    if HTTP_METHODS.include?(method)
      env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"]
      env["REQUEST_METHOD"] = method
      env[HTTP_METHOD_OVERRIDE_HEADER] = method
    end
    @app.call(env)
  end
end
end

我还将这些行添加到我的 application.rb 文件中

require 'lib/restful_jsonp_middleware.rb'
config.middleware.swap Rack::MethodOverride,Rack::RestfulJsonpMiddleware

现在,如果我使用机架中间件,我会收到此错误

rake aborted!

无法加载此类文件 -- lib/restful_jsonp_middleware.rb /home/sunny/workspace/ruby_projects/jquery_bootstrap/config/application.rb:4:in require' /home/sunny/workspace/ruby_projects/jquery_bootstrap/config/application.rb:4:in' /home/sunny/workspace/ruby_projects/jquery_bootstrap/Rakefile:5:in require' /home/sunny/workspace/ruby_projects/jquery_bootstrap/Rakefile:5:in' / home/sunny/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25:in load' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25:inload_rakefile' /home/sunny/.rvm/gems/ ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:501:in raw_load_rakefile' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:82:inblock in load_rakefile' /home/sunny/.rvm/gems/ruby-1.9.3-p194 @global/gems/rake-0.9.2.2/lib/rake/application.rb:133:in standard_exception_handling' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:81:inload_rakefile' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9。 2.2/lib/rake/application.rb:65:in block in run' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:133:instandard_exception_handling' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb :63:在run' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/bin/rake:33:in' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/bin/rake:19:in load' /home/sunny/.rvm/gems/ruby-1.9.3-p194@global/bin/rake:19:in' /home/sunny/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper :14:在eval' /home/sunny/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in'

我究竟做错了什么。

谁能帮帮我吗

4

0 回答 0