如何在 rails 5 应用程序中接受压缩请求?

How to accept gzipped requests in a rails 5 application?

以前用过this solution, but since Rails 5 deprecatedParamsParser中间件,现在不行了

如果您在 Rack::Head

之前插入中间件,这应该可以工作
config.middleware.insert_before Rack::Head, "CompressedRequests"

这应该可以解决问题

您可以使用以下命令检查应用的中间件堆栈

rake middleware

只需添加:

# config/initializers/middlewares.rb
require 'compressed_requests'

Rails.application.configure do
  config.middleware.insert_after Rack::Sendfile, CompressedRequests
end


# lib/compressed_requests.rb
# Copy the file from the article

您可以使用以下方法进行测试:

# config/routes.rb
post '/', to: 'welcome#create'

# app/controllers/welcome_controller.rb
class WelcomeController < ActionController::Base
  def create
    render json: params
  end
end

并执行请求:

curl --data-binary @<(echo "Uncompressed data" | gzip) \
     -H "CONTENT_ENCODING: gzip" \
     localhost:3000

{"Uncompressed data\n":null,"controller":"welcome","action":"create"}%

在您的 routes.rb 文件中:

post 'my_endpoint', to: 'api#my_endpoint'

你的api_controller.rb:

class ApiController < ActionController::Base
  def my_endpoint
    render json: JSON.parse(ActiveSupport::Gzip.decompress(request.body.string))
  end
end

我已经使用 Paw 客户端在全新的 Rails 5 应用程序上对此进行了测试:

如果你在Unicorns前面有NginX,那你直接告诉NginX帮你解压数据就可以了

http://www.pataliebre.net/howto-make-nginx-decompress-a-gzipped-request.html#.WBzSt-ErIUE

https://www.nginx.com/resources/admin-guide/compression-and-decompression/