Pregunta

I'm trying to use "Amplifyjs" to handle AJAX requests as does John Papa in his Pluralsight course but I'm having problems with authentication.

I am using form authentication. Everything works fine.

My problem comes with the unauthenticated requests. I can not find a way to make "amplifyjs" give back to the error function the http code (401, 403 ...) to distinguish requests that failed because they were not authenticated from requests that failed because did not met the business logic.

A request example would be:

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

Thank you.

¿Fue útil?

Solución

You can create a decoder if you want the XHR object and pass that along. It will have the error code and other information you may need.

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);
    }
});​

You can test the above code by looking at this http://jsfiddle.net/fWkhM/

Otros consejos

Thanks for your answer.

Finally, as I saw no one answered me I did something similar to what you propose:

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);
        }
    }
};

After I modify the default decoder:

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

And in the error callback I managed the returned status.

error: function (response, status) {
    if (status === "NotAuthorized") {
        logger.error(config.toasts.errorNotAuthenticated);
    } else {
        logger.error(config.toasts.errorSavingData);
    }
//more code...
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top