重定向到实际页面以响应 ajax 请求
我们有一个有状态的应用程序。当用户一段时间不活动时,会话超时,缓存的数据/对象将被销毁。
我们有一个请求过滤器,它在处理请求之前检查会话。如果会话为空,我们将重定向到登录页面。这对于正常的非 XHR 请求效果很好。
但是我们应该如何处理 XHR 请求呢?据我了解,发出对 XHR 请求的重定向仅意味着返回登录页面 html 以响应 XHR 请求,这显然不是所需的行为!
在这种情况下我们如何发出实际的页面重定向?如果这不可能,有哪些替代方案?我想很多应用程序都必须处理这个问题。
编辑:我还应该提到,由于使用处理大量 ajax 内容的应用程序框架,我们无法轻松地向 ajax 响应添加检查。
We have a stateful app. When a user is inactive for some time, the session times out, and cached data/objects are destroyed.
We have a request filter which checks the session before the request is processed. If the session is null we return a redirect to the login page. This works fine for normal, non-XHR requests.
But how should we deal with XHR requests? As far as I understand issuing a redirect to an XHR request will simply mean that the login page html is returned in response to the XHR request, which obviously is not the desired behaviour!
How can we issue an actual page redirect in this instance? If this is not possible, what alternatives are there? I imagine many apps must have to deal with this.
Edit: I should also mention that due to the use of an app framework which handles a lot of our ajax stuff we can't easily add checks to the ajax response.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您可能需要区分实际的浏览器请求和 Ajax 请求。 一些框架已经添加了自定义标头,如果您的框架没有添加的话您还可以添加这样的“X-Requested-With”标头以便能够辨别。
然后,将浏览器请求直接重定向到登录页面。对于 Ajax 请求,您应该发出
401 Unauthorized
。尽管您说框架可以处理大部分 Ajax 代码,但它仍然应该为您提供处理错误状态代码的机会(否则我会考虑迁移到另一个框架:)。
在此回调例程中,您可以使用
window.location=...
在 Javascript/客户端上发出重定向。First, you probably need to distinguish between actual browser and Ajax requests. Some frameworks already add their custom header, if yours doesn't then you could additionally add such an 'X-Requested-With' header to be able to tell.
Then, redirect the browser requests to the login page directly. For the Ajax requests, you should issue a
401 Unauthorized
.Although you say that a framework handles most of your Ajax code, it still should offer you an opportunity to hook into when it comes to handling error status codes (otherwise I'd think about moving to another framework :).
In this callback routine, you could then issue a redirect on the Javascript/client side using
window.location=...
.