本文介绍了捕获302错误,然后在Backbone.js的重定向同步方法重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的就是赶上302错误,这意味着用户没有登录,然后重定向用户到网站的登录页面。这里是我的Backbone.js的同步覆盖现在:

What I want to do is catch a 302 error which means a user is not logged in, and then redirecting that user to the login page of the website. Here's my backbone.js sync override right now:

parentSynchMethod = Backbone.sync
Backbone.sync = (method, model, success, error) ->
  try
    parentSynchMethod.apply(Backbone, arguments)
  catch error
    window.location.replace("http://localhost:8080/login")

302错误肯定是发生了,我可以看到它在网络视图中,当我使用谷歌浏览器检查网页。然而,当我设置一个断点,它永远不会抓内,错误的说法是不确定的。这是因为302不是一个真正的错误(这是黄色的,当我查看该响应的状态,而不是通常的红色的错误,还是我的地方搞乱了code。

The 302 error is definitely happening, I can see it in the network view when I inspect the page using google chrome. However, when I set a breakpoint, it never goes inside the catch, and the error argument is undefined. Is this because 302 is not a real error(it's yellow when I view the status of the response, instead of a usual red for errors, or am I messing up the code somewhere.

推荐答案

默认 Backbone.sync 不会引发当AJAX请求返回一个错误条件异常(是的,302是错误的),它离开的错误处理 $。阿贾克斯。默认同步

The default Backbone.sync doesn't raise an exception when the AJAX request returns an error condition (and yes, 302 is an error), it leaves the error handling to $.ajax. The default sync looks like this:

Backbone.sync = function(method, model, options) {
  // A bunch of bureaucratic setup and what not...

  // Make the request, allowing the user to override any Ajax options.
  return Backbone.ajax(_.extend(params, options));
};

Backbone.ajax 就是 $阿贾克斯;注意,上面是骨干当前主分支,目前发布的版本使用 $。阿贾克斯直接

and Backbone.ajax is just $.ajax; note that the above is the current master branch of Backbone, the currently released version uses $.ajax directly.

您想要做的是替换 Backbone.sync 的东西,总是迫使错误处理程序是这样的:

What you want to do is replace Backbone.sync with something that always forces an error handler like this:

error: (xhr, text_status, error_thrown) ->
    if(xhr.status == 302)
        window.location.replace('http://localhost:8080/login')
    else
        # call the supplied error handler if any

这样的事情应该做的伎俩:

Something like this should do the trick:

parentSynchMethod = Backbone.sync
Backbone.sync = (method, model, options) ->
    old_error = options.error
    options.error = (xhr, text_status, error_thrown) ->
        if(xhr.status == 302)
            window.location.replace('http://localhost:8080/login')
        else
            old_error?(xhr, text_status, error_thrown)
    parentSyncMethod(method, model, options)

如果您正在使用的骨干主分支(或之后 Backbone.ajax 阅读这是在发布的版本),那么你可以替换 Backbone.ajax 的东西,迫使错误处理程序如上离开 Backbone.sync 孤单。

If you're using the master branch of Backbone (or reading this after Backbone.ajax is in the released version), then you could replace Backbone.ajax with something that forces an error handler as above and leave Backbone.sync alone.

这篇关于捕获302错误,然后在Backbone.js的重定向同步方法重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:03