WARN不能确定响应体的内容长度。我怎么才能摆脱它?

自从升级到Rails 3.1,我在我的开发日志中看到了这条警告消息:

警告无法确定响应体的内容长度。设置响应的content-length或设置Response#chunked = true

这是什么意思,我如何删除它?有问题吗?

71121 次浏览

我向Rails-Core的一名成员提出了同样的问题:

https://twitter.com/luislavena/status/108998968859566080

答案是:

https://twitter.com/tenderlove/status/108999110136303617

是的,很好。需要清理,但没有人受伤。

另一个解决办法,删除违规行从webrick。它并没有那么有用:

cd `which ruby`/../../lib/ruby/1.9.1/webrick/ && sed -i '.bak' -e'/logger.warn/d' httpresponse.rb

(你可能需要sudo)

下面的补丁解决了这个问题在我的情况下;不用再警告我了。

204_304_keep_alive.patch

只需编辑文件httpresponse。如上面的链接所示,第205行Rb;事实上,该链接显示了对Ruby未来版本的更正。

我在通过RVM作为单个用户安装的ruby 1.9.3-p0上使用rails 3.2.0。所以我案例中的位置是:

~/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/webrick/httpresponse.rb

要修改的文件的位置取决于安装类型,RVM或非RVM,甚至多用户或单用户,所以我只是给出它的最后一部分:

.../ruby-1.9.3-p0/lib/ruby/1.9.1/webrick/httpresponse.rb

我希望这能对一些人有所帮助。

EDIT:这是提交的链接,它在ruby项目的主干分支中修改了有问题的行。

你也可以使用Thin代替默认的Webrick。 将此添加到Gemfile 宝石“薄” < /代码> < / p >

那么rails s thin将使用thin,并且警告将消失。

此问题已在Ruby的主干分支中通过提交 to webrick修复。

您可以在设置中类似地编辑这个特定的webrick文件。大致位置可以通过以下方法找到:

gem which webrick

实际编辑文件:

nano \`ruby -e"print %x{gem which webrick}.chomp %Q{.rb\n}"\`/httpresponse.rb

(或者使用您最喜欢的编辑器代替nano。)

如果您正在使用.rvm,请执行此操作来修复它…

正如若昂苏亚雷斯所提到的,所有功劳都归于他,如果你不想摆脱这个开发警告,这是你可以做的。

  1. 用你最喜欢的编辑器打开这个文件:

    ~/.rvm/rubies/<ruby-version>/lib/ruby/1.9.1/webrick/httpresponse.rb
    
  2. Go to the line that contains this(for me it was really line 206):

    if chunked? || @header['content-length']
    
  3. Change it, taken from this patch, to this:

    if chunked? || @header['content-length'] || @status == 304 || @status == 204
    
  4. Save the file and eventually restart your rails server

只是显式地将Gem添加到Gemfile中,为我摆脱了警告消息:

group :development do
gem 'webrick', '~> 1.3.1'
end

JRuby版本:如果你正在使用.rvm,请这样做来修复它…

正如若昂苏亚雷斯Kjellski所提到的,如果你想在开发中摆脱这个警告,并且你正在使用JRuby,这是你可以做的。

  1. 用你最喜欢的编辑器打开这个文件:

    ~/.rvm/rubies/jruby-<version>/lib/ruby/<1.8 or 1.9>/webrick/httpresponse.rb
    
  2. Go to the line that contains this (for me it was line 205):

    if chunked? || @header['content-length']
    
  3. Change it, taken from this patch, to this:

    if chunked? || @header['content-length'] || @status == 304 || @status == 204
    
  4. Save the file and eventually restart your rails server.

添加

config.middleware.use Rack::ContentLength

到你的application.rb文件,警告将消失,即使使用webrick。当呈现json或文本响应时,这也将在生产中正确设置Content-Length