如何在AJAX中优雅地处理设计的401状态? [英] How can I elegantly handle devise's 401 status in AJAX?

查看:185
本文介绍了如何在AJAX中优雅地处理设计的401状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用设计,使用 before_filter:authenticate_user!仅限制对已验证用户的访问。



当未经身份验证的用户尝试访问限制页面时,设计会自动导致重定向到登录页面。



所以尝试打开 http:// localhost:3000 / users / edit 将导致重定向到 http:// localhost:3000 / users / sign_in



现在,如果我定义了链接 http:// localhost:3000 / users / edit as :remote =>真正的,设计只会通过JS发出 401状态代码



我如何优雅地应对这种情况并以非远程变体的方式在覆盖 OR 重定向中显示登录对话框。



为这种情况提供一个默认策略,我只需要激活?

解决方案

是我现在选择的解决方案(在CoffeeScript语法中):

  $  - > 
$(a)。bindajax:error,(event,jqXHR,ajaxSettings,thrownError) - >
如果jqXHR.status == 401#thrownError是'Unauthorized'
window.location.replace('/ users / sign_in')

然而,这个(就是自己的)只是忘记了用户最初访问的页面,这限制了可用性。





更新:正确的重定向



在函数内,这个保存用户打算去的初始URL。



通过调用 window.location.replace(this)而不是显式地重定向到登录页面),应用程序将尝试将用户重定向到最初的目的地。



尽管仍然不可能(未经授权),但现在将是一个GET调用(而不是JS / AJAX)。因此, Devise 可以启动并将用户重定向到登录页面。



从那里开始,Devise照常运行,转发用户登录后成功登录到原始URL。


With devise one uses before_filter :authenticate_user! to restrict access to authenticated users only.

When an unauthenticated user tries to visit a restricted page anyways, devise automatically causes a redirect to the sign in page.

So trying to open http://localhost:3000/users/edit will result in a redirect to http://localhost:3000/users/sign_in.

Now, if I define the link http://localhost:3000/users/edit as :remote => true, devise will only issue a 401 status code via JS.

How can I elegantly cope with that situation and display the login dialog in an overlay OR redirect as the non-remote variant would do it?

Does devise offer a default strategy for that situation which I'd simply need to activate?

解决方案

This is the solution I chose for now (in CoffeeScript syntax):

$ ->
  $("a").bind "ajax:error", (event, jqXHR, ajaxSettings, thrownError) ->
    if jqXHR.status == 401 # thrownError is 'Unauthorized'
      window.location.replace('/users/sign_in')

However this (on it's own) just forgets about the page the user wanted to visit initially, which confines usability.

Additional (controller) logic is required for more elegant handling.

UPDATE: correct redirect

Within the function, this holds the initial URL the user intended to go to.

By calling window.location.replace(this) (instead of explicitly redirecting to the sign in page), the app will try to redirect the user to the initially intended destination.

Although still impossible (unauthorized), this will now be a GET call (instead of JS/AJAX). Therefore Devise is able to kick in and redirect the user to the sign in page.

From there on, Devise operates as usual, forwarding the user to the originally intended URL after successful sign in.

这篇关于如何在AJAX中优雅地处理设计的401状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆