【问题标题】:Amplifyjs and status codeAmplifyjs 和状态码
【发布时间】:2012-10-25 17:06:25
【问题描述】:

我正在尝试使用“Amplifyjs”来处理 AJAX 请求,就像 John Papa 在他的 Pluralsight 课程中所做的那样,但我遇到了身份验证问题。

我正在使用表单身份验证。一切正常。

我的问题来自未经身份验证的请求。我找不到让“amplifyjs”将http代码(401、403 ...)返回给错误函数的方法,以区分由于未通过身份验证而失败的请求和由于不符合业务逻辑而失败的请求。

请求示例是:

amplify.request.define("products", "ajax", {
                url: "/api/Products",
                datatype: "json",
                type: "GET"
            });
amplify.request({
                    resourceId: "products",
                    success: callbacks.success,
                    error: function (datos, status) {
                              //somecode
                           }
                });

谢谢。

【问题讨论】:

    标签: javascript ajax amplifyjs


    【解决方案1】:

    如果你想要 XHR 对象并传递它,你可以创建一个解码器。它将包含您可能需要的错误代码和其他信息。

    amplify.request.define("products", "ajax", {
        url: "http://httpstat.us/401",
        datatype: "json",
        type: "GET",
        decoder: function ( data, status, xhr, success, error ) {
            if ( status === "success" ) {
                success( data, xhr );
            } else if ( status === "fail" || status === "error" ) {
                error( status, xhr );
            } else {
                error( status, xhr );
            }
        }
    });
    
    amplify.request({
        resourceId: "products",
        success: function(data, status) {
            console.log(data, status);        
        },
        error: function(status, xhr) {
            console.log(status, xhr);
        }
    });​
    

    你可以通过查看这个http://jsfiddle.net/fWkhM/来测试上面的代码

    【讨论】:

    • 对不起,我会发表评论作为新答案。我无法在评论中正确格式化文本(或者我不知道如何)
    • @Elijah Manor,您能否提供一个可行的解决方案,说明如何将 xhr 值返回到成功回调?我创建了一个自定义解码器,但成功回调似乎总是被默认覆盖。谢谢
    • 如果你把它放在足够多的调用上,它似乎会破坏它应该给予的使用。老实说,我很困惑为什么我们只会得到默认的“成功”或“错误”。
    【解决方案2】:

    感谢您的回答。

    最后,当我看到没有人回答我时,我做了类似于你建议的事情:

    var decoder = function (data, status, xhr, success, error) {
        if (status === "success") {
            success(data, status);
        } else if (status === "fail" || status === "error") {
            try {
                if (xhr.status === 401) {
                    status = "NotAuthorized";
                }
                error(JSON.parse(xhr.responseText), status);
            } catch (er) {
                error(xhr.responseText, status);
            }
        }
    };
    

    修改默认解码器后:

    amplify.request.decoders._default = decoders.HeladeriaDecoder;
    

    并且在错误回调中我管理了返回的状态。

    error: function (response, status) {
        if (status === "NotAuthorized") {
            logger.error(config.toasts.errorNotAuthenticated);
        } else {
            logger.error(config.toasts.errorSavingData);
        }
    //more code...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2014-10-10
      • 2015-07-21
      • 2010-11-13
      相关资源
      最近更新 更多