我怎么能很好地处理色器件在AJAX 401状态? [英] How can I elegantly handle devise's 401 status in AJAX?

查看:94
本文介绍了我怎么能很好地处理色器件在AJAX 401状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

色器件 One使用的before_filter:!的authenticate_user 来限制访问认证的用户仅

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.

所以试图打开的http://本地主机:3000 /用户/编辑将导致重定向到的 HTTP://本地主机:3000 /用户/ sign_in

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

现在,如果我定义了链接的http://本地主机:3000 /用户/编辑 :远程=>真正,制定只会发出的 401状态code JS通过

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?

是否制定提供这种情况下,我想只需要激活默认的策略?

推荐答案

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

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.

更新:正确的重定向

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

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

通过调用 window.location.replace(本),而不是明确地重定向到登录页面的),应用程序会尝试将用户重定向到最初预期的目标。

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.

虽然还不可能的(未经授权),这现在将一个GET呼叫(而不是JS / AJAX)。因此,制定能踢,将用户重定向到登录页。

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.

从那里,制定工作像往常一样,在成功注册后,转发用户将原本打算URL。

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

这篇关于我怎么能很好地处理色器件在AJAX 401状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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