Ruby-on-Rails:如何摆脱“你被重定向”页面

我正在重写Devise的失败响应,以便我可以设置401状态代码。 但是,当用户登录失败时,会将其重定向到“正在重定向”链接的页面。 如果我删除它:status => 401从重定向它工作正常。

 class CustomFailure  'secure') end def respond if http_auth? http_auth else store_location! flash[:alert] = i18n_message unless flash[:notice] redirect_to redirect_url, :status => 401 end end end 

编辑

或者,我想显示flash消息并保留在同一页面上,但添加以下代码行:

 render :text => "unauthorized", :status => 401 

让ruby抱怨:

 undefined method `render' for # 

这里发生了什么事?

重定向的正确HTTP状态是30x格式(301和302是最常用的)。 默认情况下,redirect_to帮助程序在HTTP响应上设置302状态标头。 如果您覆盖它并将其设置为401,您的Web浏览器将假定响应是常规网页,并将呈现响应正文 – 在重定向中,是样板文本“您正被重定向”。

我实际上在我们的QA服务器上遇到了这个问题,但不在本地。 事实certificate,我们的memcache拦截了消息并将其呈现为200,并导致此消息出现。 这是间接由于我们的memcache设置,它们不期望从GET重定向。

 From: $document_root/cache/$uri.html /cache/$uri /cache/$uri.html $uri @memcached To: $document_root/cache/$uri.html /cache/$uri /cache/$uri.html $uri @rails 

正如@pantulis所说,如果响应代码不是3xx,浏览器将显示此标准消息

要解决此问题,您可以执行javascript重定向:

 # example with status 500: render text: "", status: 500 

仅当您确定所有用户都在使用javascript时,此选项才有效。 如果您的应用程序可能被禁用了javascript的用户浏览,那么您还应该在标准的“正被重定向”消息中包含一个noscript标记和后备信息

当我遇到这个问题时,我过去所做的就像这样:

 #app/controllers/application_controller.rb class ApplicationController < ActionController::Base after_filter :check_page_content ... private def check_page_content if response.body.include? "You are being" html_doc = Nokogiri::HTML(response.body) uri = html_doc.css('a').map { |link| link['href'] }.first response.body = "" end end end 

我正在做的是检查页面内容是否是“你正在”。 如果这是真的,我知道我不是我想成为的地方。 我只是在Javascript的帮助下将页面更新到我真正想要的位置。 我知道它不是最优雅的解决方案,但确实有帮助

快乐的黑客