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

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

问题描述

使用 devise 使用 before_filter :authenticate_user! 来限制只有经过身份验证的用户才能访问.

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

未经身份验证的用户尝试访问受限页面时,devise 会自动重定向到登录页面.

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

因此尝试打开 http://localhost:3000/users/edit 将导致重定向http://localhost:3000/users/sign_in.

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

现在,如果我将链接 http://localhost:3000/users/edit 定义为 <代码>:远程=>true,devise 只会通过 JS 发出 401 状态码.

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.

更新:正确重定向

在函数中,this 保存了用户想要访问的初始 URL.

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

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

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).因此,Devise 能够启动并将用户重定向到登录页面.

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.

从那时起,Devise 会照常运行,在成功登录后将用户转发到最初预期的 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天全站免登陆