2017-12-18 2 views
2

Ich bin auf einen api Entsendung wo eine gescheiterte Antwortausgabe auf Ziel ist:Erhalten Sie eine JSON-Antwort von einer API?

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

In Chrome Entwickler-Tool Ich kann ich eine 422-Antwort mit der Antwort von {"message":"Record not found"}

In Javascript Ich mag zu sehen bekommen die Nachricht zu erhalten und es sich einzuloggen, aber ich bin zu kämpfen, dies zu tun, hier ist mein 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 
}); 

Wie kann ich die Nachricht bekommen?

Antwort

3

fand ich einen Code, den Sie verstehen den catch-Block here sehr gut helfen können:

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

versuchen catch wie folgt aus:

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