2017-12-18 2 views
2

나는 실패 응답이 목적에 출력하는 API에 게시하도록하겠습니다 :API에서 JSON 응답 받기

크롬 개발 도구에서
return response()->json([ 
     'message' => 'Record not found', 
    ], 422); 

나는 내가 원하는 자바 스크립트에서 {"message":"Record not found"}

의 응답과 함께 422 응답을 볼 수는

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

가 어떻게 메시지를 얻을 수 있습니다

: 메시지를 받게하고 로그,하지만 난 그렇게 할 사투를 벌인거야 위해, 여기 내 자바 스크립트입니까?

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

답변

3

나는 당신이 아주 잘 here catch 블록을 이해하는 데 도움이 할 수있는 코드를 발견
1

시도 같은 catch에 :

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