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

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

问题描述:

我覆盖了Devise的失败响应,以便我可以设置401状态代码。但是,当用户登录失败时,将被重定向到具有您被重定向链接的页面。如果我从重定向中删除这个:status => 401 ,它可以正常工作。

I am overriding Devise's failure response so that I can set a 401 status code. However, when the user fails to sign in, they are redirected to a page with a "you are being redirected" link. If I remove this :status => 401 from the redirect it works fine.

class CustomFailure < Devise::FailureApp
    def redirect_url
      new_user_session_url(:subdomain => '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消息并保留在同一页面,但添加以下代码行:

edit

Alternatively I would like to display the flash message and remain on the same page but adding this line of code:

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

导致ruby抱怨:

undefined method `render' for #<CustomFailure:0x00000103367f28>

这里发生了什么?

重定向的适当HTTP状态为30x格式(301和302是最常用的)。默认情况下,redirect_to帮助器在HTTP响应中设置302状态标题。如果您重写并将其设置为401,您的Web浏览器将假定响应是常规网页,并将呈现响应正文 - 重定向是您正被重定向的样板文本。

Proper HTTP statuses for a redirection are in the 30x form (301 and 302 being the most frequently used). By default, the redirect_to helper sets a 302 status header on the HTTP response. If you override that and set that to a 401, your web browser will assume that the response is a regular web page and will render the response body --which, in a redirection, is the boilerplate text "You are being redirected".