panthro
panthro

Reputation: 24099

Get a JSON response from an API?

I'm posting to an api where a failed response is output on purpose:

return response()->json([
        'message' => 'Record not found',
    ], 422);

In Chrome dev tools I can see I get a 422 response with the response of {"message":"Record not found"}

In javascript I wish to get the message and log it, but i'm struggling to do so, here's my javascript:

axios.post('/api/test', {
    name: 'test'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error) //this is Error: Request failed with status code 422
    console.log(error.message); //this is blank
});

How can I get the message?

Upvotes: 2

Views: 86

Answers (2)

amhev
amhev

Reputation: 333

try to catch like this:

.catch(function(error){
    console.log(error);
    if (error.response) {
       console.log(error.response.data.message);
    }
});

Upvotes: 1

Maraboc
Maraboc

Reputation: 11093

I found a code that can help you understand the catch block very well here :

axios.post('/api/test', {
    name: 'test'
})
.then((response) => {
    // Success
})
.catch((error) => {
    // Error
    if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        // console.log(error.response.data);
        // console.log(error.response.status);
        // console.log(error.response.headers);
    } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        console.log(error.request);
    } else {
        // Something happened in setting up the request that triggered an Error
        console.log('Error', error.message);
    }
    console.log(error.config);
});

Upvotes: 3

Related Questions