Output REST API Status Displayed In Postman To AJA

2019-09-14 06:59发布

问题:

In Postman, I can successfully communicate with my REST API. I can put my API server in various artificial states to represent 2xx, 4xx & 5xx errors which I can successfully view in Postman as follows:

Postman is able to collect this info, regardless of whether or not the API server is running & it appears to be a generic status response, vs. a response that the API app produces.

My question is, how do I output this into a console.log() in my Javascript App?

In my instance, I want to output the status inside an AJAX function at the backend of a form submit:

$.ajax(settings).done(function(response, jqXHR, data) {
        console.log("Return Code: " + data.status);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        console.log("Return Code: " + ??? );
    });
});

My data.status works fine when I get a success, but presumably there is a variable that I can tap into that is the generic status message?

回答1:

You can get the returned status code from the status property of the jqXHR object:

.fail(function(jqXHR, textStatus, errorThrown) {
    console.log("Return Code: " + jqXHR.status);
});

Working example