3

PluralsightコースのJohnPapaと同じように、「Amplifyjs」を使用してAJAXリクエストを処理しようとしていますが、認証に問題があります。

フォーム認証を使用しています。すべてが正常に動作します。

私の問題は、認証されていないリクエストにあります。「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
                           }
                });

ありがとうございました。

4

2 に答える 2

6

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/を見ると、上記のコードをテストできます。

于 2012-11-07T06:16:09.103 に答える
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...
}
于 2012-11-07T18:30:57.843 に答える