【问题标题】:How to intercept and rewrite damaged JSON calls with Middleware如何使用中间件拦截和重写损坏的 JSON 调用
【发布时间】:2014-03-27 14:47:11
【问题描述】:

我正在努力寻找执行此操作的最佳位置。我的中间件是这样的:

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

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

【问题讨论】:

    标签: ruby-on-rails json rack middleware env


    【解决方案1】:

    我认为这个问题和这里一样:https://stackoverflow.com/questions/22712663/getting-a-routing-error-when-my-routes-are-clearly-marked 和这里I have a third party service that I believe is sending me malformed JSON

    据我了解,您想修复一些传入的请求数据。

    作为一个简化的例子:

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

    我在修复程序中将 something 更改为 phoet

    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"}
    

    【讨论】:

    • 很公平。这结束了这部分,基本上在我的另一个问题中得到了回答。
    • @Trip 我可能会误解你的问题。您还有什么其他问题?
    • 无论我在 Rack 引擎中重写哪个 URL,Rails 都找不到该路由,除非我将路由重写到 /,它重定向到 /quizzesstackoverflow.com/questions/22712663/…
    • 为什么需要重写?
    • 感谢您的回复。一年后我又回来了,终于明白了这一点。
    猜你喜欢
    • 2014-02-10
    • 2015-04-16
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多