3

我这里发生了一些非常奇怪的事情。我有一个模型,我正在尝试获取。我可以查看 Fiddler 中的调用或手动调用我的 API 服务,然后我会得到我期望返回的 JSON,但是 fetch 方法总是在 Backbone 中引发错误。它没有告诉我原因,并且 responseText 是空的。在提琴手中,服务返回 200。

这是调用代码...

    this.createSession = function (sessionId) {
            var that = this;

            CookieManager.CreateSession(sessionId);
            var sessionData = new Authentication.Response({
                id: sessionId 
            });

            sessionData.fetch({
                success: function () {
                    that.storeData(sessionData);
                },
                error: function (model, xhr) {
                    if (console !== undefined && console !== null) {
                        console.log('Unable to load session data: ' + xhr.responseText);
                    }
                    throw new Error('Unable to load session data');
                }
            });
        };

和有关的模型...

define(['ministry', 'moment'],
function (Ministry) {
    var authRequest = Ministry.Model.extend({

        name: 'Auth Request',
        urlRoot: '/api/auth',

        defaults: {
            id: undefined,
            requestSource: undefined,
            apiKey: undefined,
            username: undefined,
            password: undefined,
            dateCreated: undefined,
            lastLoggedIn: undefined
        },

        generatedHash: undefined,

        parse: function(attributes, response) {
            var hashUrl = response.xhr.getResponseHeader('location');
            var elements = hashUrl.split("/");
            this.generatedHash = attributes.id = elements[elements.length - 1].toLowerCase();
            return attributes;
        },

        validate: function (attributes) {
            if (attributes.requestSource === undefined || attributes.requestSource == null || attributes.requestSource == '') {
                return "The attribute 'requestSource' is required";
            }
            if (attributes.apiKey === undefined || attributes.apiKey == null || attributes.apiKey == '') {
                return "The attribute 'apiKey' is required";
            }
            if (attributes.username === undefined || attributes.username == null || attributes.username == '') {
                return "The attribute 'username' is required";
            }
            if (attributes.password === undefined || attributes.password == null || attributes.password == '') {
                return "The attribute 'password' is required";
            }
            return null;
        }
    });

    // Return as two types for syntactic sugar reasons.
    return {
        Request: authRequest,
        Response: authRequest
    };
});

该模型扩展了我的通用根模型,其代码在这里...

  var ministryModel = Backbone.Model.extend({

        name: 'Unnamed Model',

        initialize: function (options) {
            this.options = options || {};
            Backbone.Model.prototype.initialize.call(this, options);
            if (this.options.name) {
                this.name = this.options.name;
            }

            this.on('invalid', function (model, error) {
                if (console !== undefined) {
                    console.log(error);
                    console.log(model);
                }
                throw (new Error(error));
            });
        },

        fetch: function (options) {
            this.trigger('fetching', this, options);
            return Backbone.Model.prototype.fetch.call(this, options);
        }
    });

错误回调总是被调用,我不知道为什么。在 Fiddler 中,我通过直接调用 API 得到以下信息......

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 19 Aug 2013 16:12:00 GMT
Content-Length: 213

{"id":"bba5e742d1af3de5921e8df0a1818530789c202a","dateCreated":"2013-07-22T17:57:20.143","lastLoggedIn":"2013-08-19T17:08:29.67","username":"tiefling","apiKey":"ka73nd9s7n2ls9f3ka2n5p2k","requestSource":"website"}

这在从 Chrome 询问电话时......

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 19 Aug 2013 16:08:29 GMT
Content-Length: 213

{"id":"bba5e742d1af3de5921e8df0a1818530789c202a","dateCreated":"2013-07-22T17:57:20.143","lastLoggedIn":"2013-08-19T17:08:29.67","username":"tiefling","apiKey":"ka73nd9s7n2ls9f3ka2n5p2k","requestSource":"website"}

两者都显示 200,但在 Fiddler 中显示的图标略有不同 - Chrome 通话图标是一个红色圆圈,但除此之外,一切看起来都很笨拙。

欢迎任何想法,我现在已经碰到了这个问题。

附加:如果我单步执行代码,当我到达 fetch 调用时,'sessionData' 对象中的属性根本没有更新。该对象与执行 fetch 方法之前的对象完全相同。

更新:自从我第一次写这个以来,就我从 Fiddler 看到的,代码现在已经完全停止了调用。这在早期工作,但现在似乎无形地失败,没有迹象表明错误可能是什么。调试 API 代码表明现在根本没有调用服务上的 GET 方法。

进一步更新:除了删除错误/成功回调之外,无需更改任何代码,这开始工作(有点)。如果我在 fetch 调用之后放置一个断点,那么它会完全正常工作(从我在 Fiddler 中看到的 - 我无法检查应用程序,因为成功回调是无线的)。如果我取出断点,它现在会部分失败(Fiddler 中的红色圆圈,但响应为 200)。

这似乎是某种竞争条件?

我尝试使用“完整”回调来获取信息以使用 textStatus,但这只是说“错误”——不是特别有用!

4

1 回答 1

1

我终于找到了答案;这在上面的代码中并不明显。正在从这样的更高方法调用调用代码......

                    var authData = SiansPlanApp.session.getData(this.$loginUsername.val(), this.$loginPassword.val());

                authData.save(authData.attributes, {
                    success: function() {
                        if (authData.generatedHash !== undefined && authData.generatedHash !== null && authData.generatedHash !== '')
                            MyApp.session.createSession(authData.generatedHash);
                        that.redirectToOrigin();
                        $.fancybox.close();
                    },
                    error: function (model, xhr) {
                        if (console !== undefined && console !== null) {
                            console.log('Login attempt failed: ' + xhr.responseText);
                        }
                        that.displayError('Username or password not recognised');
                        $.fancybox.close();
                    }
                });

如您所见,createSession 方法之后立即调用了redirectToOrigin() - 虽然没有显示,但只要说该方法将页面重定向到根就足够了。失败的原因很简单——一旦通过重定向运行初始创建调用,就没有时间进行任何回调。

于 2013-08-19T17:24:02.653 回答