请求失败时,无法在JSONP代理回调中获得响应

时间:2014-10-03 00:08:17

标签: javascript extjs extjs4

我正在尝试为所有商店添加一些逻辑。我希望这个逻辑在通过应用商店

定义的逻辑之前执行

基本上,我想要一大块代码来查看来自服务器的响应,如果它特别回复,做一些事情,如果没有,那么通过调用this.callParent()继续进行任何事情我猜测。

这似乎做了我想做的事,但它已经过时了,不适用于4.2.1

http://www.learnsomethings.com/2011/09/01/adding-some-error-detection-to-all-your-extjs-stores-with-one-simple-block-of-code/

现在这就是我在4.2.1中做的事情,它似乎正在运作

Ext.define('App.overrides.Data.Store', {
    override: 'Ext.data.Store',
    load: function (options) {
        if (options != null) {
            options.callback = storeLoad;
        }
        this.callParent(arguments);
    }
});

storeLoad: function (records, operation, success) {
    // operation.response is undefined on failures...       
}

但正如上面的评论所指出的,如果请求以400,401,500等代码失败,我将无法获得operation.response

如果我浏览ExtJS在加载时生成的确切URL,该错误应该返回我想要的字符串的错误,我得到这个:

Ext.data.JsonP.callback4({"Message":"The string!"})

此输出由我的.NET Web API后端返回:

actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, PortalResources.THE_STRING);

如果我将HttpStatusCode更改为OK,我将能够在storeLoad上方获得回复,但如果状态<> 200。

我认为这是我的后端没有正确回复,但是ExtJS和/或我对它的理解似乎是问题所在。我认为这是我的商店/代理的定义方式,因为当服务器返回状态为<>时200,我甚至没有看到Chrome调试器中的响应内容。

这是我的一家商店:

Ext.define('Customer_Portal_UI.store.Contact', {
    extend: 'Ext.data.Store',
    model: 'Customer_Portal_UI.model.Contact',
    limitParam: false,
    pageParam: false,
    startParam: false
});

//.......

Ext.create('Customer_Portal_UI.store.Contact', {
    storeId: 'myContactStore',
    proxy: {
        type: 'jsonp',
        url: this.Urls.contactGetAllApiUrl,
        headers: { 'Content-type': 'application/json' },
        reader: { type: 'json', root: 'Contacts' }
    }
});

我尝试了提到in there的覆盖,但同样的问题。失败时响应未定义。我一直在框架链中爬行,我似乎无法找到适当的覆盖来执行此操作。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我切换到一个vanilla Ajax代理,现在我可以在失败的请求中正确检索响应文本。

这就是我最终做的事情:

Ext.Ajax.on('requestexception', function (conn, response, options) {
        //If an AJAX request receives this response text & status, log the user out.
        //regardless of the resource that was queried
        if (response.responseText == GlobalVars.loginError && response.status == 408) {

            //the following stops extra logic from executing (if you had configured a 'failure' option on your request in the controller)
            delete options.failure;
            delete options.callback;

            //show the user a message box with an OK button that when clicked logs the user out...
            Utils.maxIdleReached();
        }
        else {
            //do nothing...
            //let controller logic do it's thing then as individual store/requests have 'failure' options configured for each....
        }
});

这会捕获异常(接收状态代码为400,401,408,404,500等的请求),无论是通过商店加载还是普通Ext.Ajax.request完成。