Access http body on Dojo request error

杀马特。学长 韩版系。学妹 提交于 2020-01-03 22:00:23

问题


My webservice puts details about the occoured error in the http body. How can I access this details in a dojo request.

For example the http error looks like this:

HTTP/1.1 500 Internal Server Error
Transfer-encoding: chunked
Content-type: application/json
Date: Tue, 18 Sep 2012 18:47:31 GMT

15
This is my exception!
0

My Dojo Request looks like this:

require(["dojo/dom", "dojo/on", "dojo/request",
        "dojo/json", "dojo/domReady!"],
    function(dom, on, request, JSON){
        // Results will be displayed in resultDiv
        var resultDiv = dom.byId("errorResult");

        // Attach the onclick event handler to the makeRequest button
        on(dom.byId('errorButton'),"click", function(evt){
            request.get("./rest/test/error", {
                // Parse data from JSON to a JavaScript object
                handleAs: "json"
            }).then(function(data){
                resultDiv.innerHTML = "Username: " + data.name + "</br>Role:" + data.role;
            },
            function(error){
                // Display the error returned
                resultDiv.innerHTML = error;
            });
        });
    }
);

The displayed error in the is:

RequestError: Unable to load ./rest/test/error status: 500

And what i would like to have there is the text in the body:

This is my exception!

回答1:


Have a look at my answer to How to retreive XHR response code (+timestamp) of AMD'ized Dojo?

Use deferred.response.then instead of deferred.then:

var deferred = request.get("./rest/test/error", { handleAs: "json" });

deferred.response.then(
    // success
    function(response) {
        console.log("data:", response.data);      // parsed json
        console.log("http body:", response.text); // raw text
    },
    // error
    function(error) {
        var response = error.response;
        console.log("http body:", response.text);
    }
);

See it in action at jsFiddle: http://jsfiddle.net/phusick/SGh5M/




回答2:


When I've used dojo for Ajax requests, the error method always had more than one parameter. I think the first param is the request that was sent and the second param is the response or exception.

Try adding a second param to your method and see if that contains what you need.



来源:https://stackoverflow.com/questions/12483149/access-http-body-on-dojo-request-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!