2017-12-18 253 views
2

我張貼到一個API,其中一個失敗的迴應是故意的輸出:從API獲取JSON響應?

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

在Chrome瀏覽器開發工具,我可以看到我得到的​​

在javascript中我希望響應422響應獲取消息並記錄下來,但我很努力這麼做,這裏是我的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 
}); 

我怎樣才能得到消息?

回答

3

我發現了一個代碼,可以幫助您瞭解catch塊很好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); 
}); 
1

嘗試catch這樣的:

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