【问题标题】:"render :nothing => true" returns empty plaintext file?"render :nothing => true" 返回空的纯文本文件?
【发布时间】:2011-06-05 15:49:50
【问题描述】:

我使用的是 Rails 2.3.3,我需要创建一个发送帖子请求的链接。

我有一个看起来像这样的:

= link_to('Resend Email', 
  {:controller => 'account', :action => 'resend_confirm_email'}, 
  {:method => :post} )

这会在链接上产生适当的 JavaScript 行为:

<a href="/account/resend_confirm_email" 
  onclick="var f = document.createElement('form'); 
  f.style.display = 'none'; 
  this.parentNode.appendChild(f); 
  f.method = 'POST'; 
  f.action = this.href;
  var s = document.createElement('input'); 
  s.setAttribute('type', 'hidden'); 
  s.setAttribute('name', 'authenticity_token'); 
  s.setAttribute('value', 'EL9GYgLL6kdT/eIAzBritmB2OVZEXGRytPv3lcCdGhs=');
  f.appendChild(s);
  f.submit();
  return false;">Resend Email</a>'

我的控制器动作正在运行,并设置为不渲染:

respond_to do |format|
  format.all { render :nothing => true, :status => 200 }
end

但是当我点击链接时,我的浏览器会下载一个名为“resend_confirm_email”的空文本文件。

什么给了?

【问题讨论】:

标签: ruby-on-rails rest link-to


【解决方案1】:

从 Rails 4 开始,head 现在比 render :nothing 更受欢迎。1

head :ok, content_type: "text/html"

# or (equivalent)

head 200, content_type: "text/html"

优于

render nothing: true, status: :ok, content_type: "text/html"

# or (equivalent)

render nothing: true, status: 200, content_type: "text/html"

它们在技术上是相同的。如果您查看使用 cURL 的响应,您将看到:

HTTP/1.1 200 OK
Connection: close
Date: Wed, 1 Oct 2014 05:25:00 GMT
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
X-Runtime: 0.014297
Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache

但是,调用 head 提供了比调用 render :nothing 更明显的替代方法,因为现在明确表示您只生成 HTTP 标头。


  1. http://guides.rubyonrails.org/layouts_and_rendering.html#using-head-to-build-header-only-responses

【讨论】:

  • 因为这也适用于 Rails 3,它也应该是首选的解决方案(但显然 OP 在 Rails 2.3 应用程序上,所以选择的答案是合适的)。
  • head 200 对我产生了 304 响应(在 Rails 4.1.6 上)。控制台显示 200 状态代码,但 chrome(网络面板)显示 304。render :nothing =&gt; true 方法有效。
  • 如果只返回一个标头,是否需要内容类型?
【解决方案2】:

更新:这是旧版 Rails 的旧答案。对于 Rails 4+,请参阅下面 William Denniss 的帖子。

在我看来,响应的内容类型不正确,或者在您的浏览器中没有正确解释。仔细检查您的 http 标头以查看响应的内容类型。

如果不是text/html,可以尝试手动设置内容类型如下:

render :nothing => true, :status => 200, :content_type => 'text/html'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 2017-09-11
    • 2016-06-15
    • 2011-10-05
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    相关资源
    最近更新 更多