Rails/Rack: “ArgumentError: invalid %-encoding” for POST data

扶醉桌前 提交于 2019-11-30 18:43:34

I'm guessing your partner is probably POSTing the data to you as "x-www-form-urlencoded", making Rack try to parse it that way. If they can change what they're sending, I suspect making their content-type "text/xml" will fix this.

If you can't get them to change what they send, then yes, I think you'd have to use Rack middleware (or monkeypatching). Although you could poke around the Rack source, maybe there's a setting to avoid doing any parsing.

In my case the reason was extra newlines after the headers and before the request body. I'm guessing there is Content-Length inconsistency which throws off the parser. If you are setting headers programmatically make sure they don't have trailing newlines.

mltsy

There's some debate in various forums as to where the responsibility lies for catching invalid encoding errors in request body content, but neither rack nor rails handles it, both leaving it to the app to handle. To work around invalid %-encoding in POST data in my app, I used a similar solution to this related question: Rails ArgumentError: invalid %-encoding

I added this middleware in app/middleware/invalid_post_data_interceptor.rb to intercept invalid post data:

class InvalidPostDataInterceptor
  def initialize(app)
    @app = app
  end

  def call(env)
    request_content = Rack::Request.new(env).POST rescue :bad_form_data

    headers = {'Content-Type' => 'text/plain'}

    if request_content == :bad_form_data
      [400, headers, ['Bad Request']]
    else
      @app.call(env)
    end
  end
end

Then added it to the middleware stack by adding this to application.rb:

config.middleware.insert_before Rack::Runtime, "InvalidPostDataInterceptor"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!