ruby on rails -如何用中间件拦截和重写损坏的JSON调用



我正试图找到最好的地方做这件事。我的中间件是这样的:

class Fixer
  def initialize app
    @app = app
  end
  def call env
   if env["HTTP_ORIGIN"] == "https://where_i_expect_it_to_come_from.com/"
     env['rack.input'] = StringIO.new('{"yo":"momma"}') # <--  But this info is not actually written before the call is passed!
   end
   env['rack.input'].rewind
   status, headers, response = @app.call env
   return [status, headers, response]
  end
end
Rails.application.config.middleware.insert_before ActionDispatch::ParamsParser, Fixer

似乎即使我在这里重写调用,信息实际上也没有被正确地重写。有什么想法,我可以有我的内容写在它冒泡之前?

我认为这个问题是相同的这里:https://stackoverflow.com/questions/22712663/getting-a-routing-error-when-my-routes-are-clearly-marked和这里我有一个第三方服务,我相信是发送给我畸形的JSON

根据我的理解,你想修复一些传入的请求数据。

作为一个简化的例子:

curl -X PUT -d "user[name]=something" http://localhost:3000/users/123

i change something to phoet in fixer

class Fixer
  def initialize(app)
    @app = app
  end
  def call(env)
    env['rack.input'] = StringIO.new("user[name]=phoet")
    @app.call(env)
  end
end

加到application.rb

config.middleware.insert_before "ActionDispatch::ParamsParser", "Fixer"

当我现在请求我的应用程序时,我看到日志

[localhost] [fdff4eb0-8387-41] Started PUT "/users/123" for 127.0.0.1 at 2014-03-30 13:16:02 -0400
[localhost] [fdff4eb0-8387-41] Processing by UsersController#update as */*
[localhost] [fdff4eb0-8387-41]   Parameters: {"user"=>{"name"=>"phoet"}, "id"=>"123"}

相关内容

  • 没有找到相关文章

最新更新