无效请求:无效的HTTP格式,Rails中的解析失败

传递具有特殊字符的字符串时,我收到无效请求:无效的HTTP格式,解析失败错误。 日志中的错误如下。

我的请求:

http://localhost:3000/search/% 

错误日志:

  Invalid request: Invalid HTTP format, parsing fails. /.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/request.rb:84:in `execute' /.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/request.rb:84:in `parse' /.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/connection.rb:39:in `receive_data' /.rvm/gems/ruby-1.9.3-p545/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run_machine' /.rvm/gems/ruby-1.9.3-p545/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run' /.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/backends/base.rb:73:in `start' /.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/server.rb:162:in `start' /.rvm/gems/ruby-1.9.3-p545/gems/rack-1.5.2/lib/rack/handler/thin.rb:16:in `run' /.rvm/gems/ruby-1.9.3-p545/gems/rack-1.5.2/lib/rack/server.rb:264:in `start' /.rvm/gems/ruby-1.9.3-p545/gems/railties-4.0.2/lib/rails/commands/server.rb:84:in `start' /.rvm/gems/ruby-1.9.3-p545/gems/railties-4.0.2/lib/rails/commands.rb:76:in `block in ' /.rvm/gems/ruby-1.9.3-p545/gems/railties-4.0.2/lib/rails/commands.rb:71:in `tap' /.rvm/gems/ruby-1.9.3-p545/gems/railties-4.0.2/lib/rails/commands.rb:71:in `' bin/rails:4:in `require' bin/rails:4:in `' 

可能是什么问题呢? 请建议我解决这个问题的想法。

如何在获得以下错误的同时重定向到另一个页面?

在此处输入图像描述

更新您的nginx配置文件,如下所示,并在公用文件夹中创建400.html文件。

服务器{listen 80;

  root /public; # <--- be sure to point to 'public'! error_page 400 /400.html; location = /400.html { internal; } 

}

%是url中的特殊字符,用于url-encoding你应该使用另一个通配符,比如* http:// localhost:3000 / search / *

为处理此类错误,会引发许多exception。 像ActiveRecord::RecordInvalid ActiveRecord::RecordNotFound 。 但这是模型例外。 使用控制器,我们有ActionController::RoutingError ActionController::BadRequest ,它们与路由,映射url相关

所以当你得到400错误时,这是​​一个bad request error ,所以你必须通过调用一个方法来处理它,该方法将呈现一个html页面作为响应

试试这个

 class ApplicationController < ActionController::Base rescue_from ActionController::RoutingError, :with => :route_not_found_error rescue_from ActionController::BadRequest, :with => :bad_request_error resue_from StandardError, :with => :render_server_error protected def route_not_found_error render "shared/404", :status => 404 end def bad_request_error render "shared/400", :status => 400 end def render_server_error render "shared/500", :status => 500 end end 

在app / views / shared中添加您的404.html400.html500.html页面